Python .get nested Json values - python

I have a json file with the following example json entry:
{
"title": "Test prod",
"leafPage": true,
"type": "product",
"product": {
"title": "test product",
"offerPrice": "$19.95",
"offerPriceDetails": {
"amount": 19.95,
"text": "$19.95",
"symbol": "$"
},
"media": [
{
"link": "http://www.test.com/cool.jpg",
"primary": true,
"type": "image",
"xpath": "/html[1]/body[1]/div[1]/div[3]/div[2]/div[1]/div[1]/div[1]/div[1]/a[1]/img[1]"
}
],
"availability": true
},
"human_language": "en",
"url": "http://www.test.com"
}
I can post via python script this to my test server perfectly when I use:
"text": entry.get("title"),
"url": entry.get("url"),
"type": entry.get("type"),
However I cannot get the following nested item to upload the values, how do I structure the python json call to get a nested python json entry?
Ive tried the below without success, I need to have it as .get because there are different fields currently in the json file and it errors out without the .get call.
"Amount": entry.get("product"("offerPrice"))
Any help on how to structure the nested json entry would be very much appreciated.

You need to do:
"Amount": entry.get("product", {}).get("offerPrice")
entry.get("product", {}) returns a product dictionary (or an empty dictionary if there is no product key).

Related

JSON EXtraction in Python

I am trying to extract a specific part of the JSON but I keep on getting errors.
I am interested in the following sections:
"field": "tag",
"value": "Wian",
I can extract the entire filter section using:
for i in range(0,values_num):
dedata[i]['filter']
But if I try to filter beyond that point I just get errors.
Could someone please assist me with this?
Here is the JSON output style:
{
"mod_time": 1594631137499,
"description": "",
"id": 82,
"name": "Wian",
"include_custom_devices": true,
"dynamic": true,
"field": null,
"value": null,
"filter": {
"rules": [
{
"field": "tag",
"operand": {
"value": "Wian",
"is_regex": false
},
"operator": "~"
}
],
"operator": "and"
}
}
You are probably trying to access the data in rules but since its an array, you have to specifically access that array by getting the [0] index.
You could simplistically just use .get('<name>') as shown below:
dedata['filter']['rules'][0].get('field'))
Likewise for value:
dedata[i]['filter']['rules'][0]['operand'].get('value')
comment out the for loop and try without it and [i] and see if it works

Using Response of Confluence Rest API

I am performing bulk operation of creating Space and Pages in our Confluence Cloud instance. I am not particularly a programmer. Need some assistance in using the response we are getting after running the APIs using Python. The output is in Json format. If this is the output can you please let me know how can I access the title and ID -
{
"content": {
"id": "398852913",
"type": "page",
"status": "current",
"title": "Test Project Name 1 SOW",
"childTypes": {},
"macroRenderedOutput": {},
"restrictions": {},
"_expandable": {
"container": "",
"metadata": "",
"extensions": "",
"operations": "",
"children": "",
"history": "/rest/api/content/398852913/history",
"ancestors": "",
"body": "",
"version": "",
"descendants": "",
"space": "/rest/api/space/TestSpace1",
},
"_links": {
"webui": "/spaces/TestSpace1/pages/398852913/Test+Project+Name+1++SOW",
"self": "https://enerzinx.atlassian.net/wiki/rest/api/content/398852913",
"tinyui": "/x/MQPGFw",
},
},
"title": "Test Project Name 1 SOW",
"excerpt": "file-list",
"url": "/spaces/TestSpace1/pages/398852913/Test+Project+Name+1++SOW",
"resultGlobalContainer": {
"title": "TestSpace1",
"displayUrl": "/spaces/TestSpace1",
},
"breadcrumbs": [],
"entityType": "content",
"iconCssClass": "aui-iconfont-page-default",
"lastModified": "2020-06-24T06:17:32.333Z",
"friendlyLastModified": "Jun 24, 2020",
"score": 0.59390986,
}
If your response is a string in JSON format first you will need to parse the JSON into a dictionary. For this you can use the json module, which is part of the set of standard modules. After parsing the JSON you can then access the keys using a dictionary lookup.
>>> import json
>>>
>>> json_string = '{"foo": "bar"}'
>>> json_dict = json.loads(json_string)
>>> json_dict["foo"]
'bar'
It looks like your response JSON will yield a nested dictionary, so the path for the title will look something like json_dict["foo"]["bar"].

Printing each instance of a single line item from a JSON using python

Does anyone know how to print and multiple instances of the same line from a JSON output?
The code I wish to decipher looks something similar to:
[
{
"project": {
"id": 6514847,
"name": "Trial_1",
"code": "123",
"created_at": "2014-10-08T04:22:14Z",
"updated_at": "2017-04-11T00:32:43Z",
"starts_on": "2014-10-08"
}
},
{
"project": {
"id": 6514864,
"name": "Trial_2",
"code": "456",
"created_at": "2014-10-08T04:26:39Z",
"updated_at": "2017-04-11T00:32:46Z",
"starts_on": "2014-10-08"
}
},
{
"project": {
"id": 12502453,
"name": "Trial_3",
"code": "789",
"created_at": "2016-12-08T05:14:38Z",
"updated_at": "2017-04-11T00:32:38Z",
"starts_on": "2016-12-08"
}
}
]
This code was a request.get()
I know I can print a single instance of this using
req = requests.get(url, headers=headers)
read_req = req.json()
trial = read_req['project']['code']
print(trial) #123
The final product I wish to see is linking each Project Name to its relevant Project Code.
You have a list of dicts of dicts. To iterate over each "project" dict you just use a for loop.
for entry in read_req:
trial = entry['project']['code']
print(trial)
In this case, each time through the loop entry will be a dictionary containing the "project" key.
You need for loop.
read_req = req.json()
for project in read_req:
print(project['project']['code'])
This should work for you:
assuming jsontxt is having input data
for i in range(0,len(jsontxt)):
print jsontxt[i]['project']['name'], jsontxt[i]['project']['code']

PayPal:Python Incoming JSON request does not map to API request

Am trying to integrate paypal sdk in my website using the paypal-python-SDK. When I type the item_list manually like this:
{"name": "Sparzy", "sku": "music beat", "price": "25.0", "currency": "USD", "quantity": 1}
But when I try to add it in form of a variable e.g.
itemlist = {"name": "Sparzy", "sku": "music beat", "price": "25.0", "currency": "USD", "quantity": 1}
I get the following error:
Payment Error: {u'message': u'Incoming JSON request does not map to API request', u'debug_id': u'394fa35b1b301', u'name': u'MALFORMED_REQUEST', u'information_link': u'https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST'}
I really need it as a variable so that I can dynamically generate the list when a user add producs to cart. Thanks for your help.
I think you are trying to use dictonnary as JSON. Both syntaxes are similar but dictionnaries are Python structure while JSON is a data format.
In comments you said use your itemlist dictionnary like:
"transactions": [{
"item_list": { "items": [ itemlist ] },
"amount": { "total": total, "currency": "USD" },
"description": "This is the payment transaction description."
}]
If this is your entiere JSON data you want to send, you can do something like:
dict_data = "transactions": [{
"item_list": { "items": [ itemlist ] },
"amount": { "total": total, "currency": "USD" },
"description": "This is the payment transaction description."
}])
json_data = json.dumps(dict_data)
json.dumps() take a structure and parse it in JSON formatted string.
If you are doing something like:
json_data = "transactions": [{
"item_list": { "items": [ json.dumps(itemlist) ] },
"amount": { "total": total, "currency": "USD" },
"description": "This is the payment transaction description."
}])
You are wrong because element transacations:item_list will be a list of strings and not a list of dicts.
It's important to understand that JSON is just a way to format a structure, you could parse you dict in XML in the exact same way by example.
So be sure to compute data you want to send in a dictionnary first, then, at the really end, parse the whole data in JSON string.

Best way to parse sections of json in python3 to separate items in list

First off, I'm having trouble Googling this question since I don't know all of the terminology (so really, giving me the proper terms to use in my Google search would be just as useful in this question).
I have some JSON that I need to parse in python, put each JSON string in a list after its been parsed(List, not array for Python correct?) and then I am going to go through that list to push the JSON content back to my source.
So as of now, I can parse out a section of JSON that I want, but I am not sure how to then get down to just printing the section between brackets. For example, I want to get each section (brackets) in this block of code to be in a separate JSON line:
{
"components": [
{
"self": "MY URL",
"id": "ID",
"name": "NAME",
"description": "THIS IS DESC",
"isAssigneeTypeValid": false
},
{
"self": "MY URL 2",
"id": "ID",
"name": "name",
"isAssigneeTypeValid": false
},
{
"self": "URL 3",
"id": "ID",
"name": "NAME 3",
"description": "DESC",
"isAssigneeTypeValid": false
}
]
}
There is a lot more JSON in my file, but using this, I can get it down to just returning the text above.
datas = json.loads(data)
print(datas['components'])
So my question is how would I just print one block? Or access the first 'self' section?
Here's how you can iterate over that data, converting each dict in the "components" list back into JSON strings:
import json
data = '''
{
"components": [
{
"self": "MY URL",
"id": "ID",
"name": "NAME",
"description": "THIS IS DESC",
"isAssigneeTypeValid": false
},
{
"self": "MY URL 2",
"id": "ID",
"name": "name",
"isAssigneeTypeValid": false
},
{
"self": "URL 3",
"id": "ID",
"name": "NAME 3",
"description": "DESC",
"isAssigneeTypeValid": false
}
]
}
'''
datas = json.loads(data)
for d in datas['components']:
print(json.dumps(d))
output
{"self": "MY URL", "description": "THIS IS DESC", "id": "ID", "isAssigneeTypeValid": false, "name": "NAME"}
{"self": "MY URL 2", "id": "ID", "isAssigneeTypeValid": false, "name": "name"}
{"self": "URL 3", "description": "DESC", "id": "ID", "isAssigneeTypeValid": false, "name": "NAME 3"}
If you have a valid json document then you can simply iterate over the list of components. Assuming you name the file <id>.json then you can simply do:
datas = json.loads(data)
for component in datas['components']:
with open("{}.json".format(component['id']), 'w') as f:
json.dump(component, f)
When you read it in, a JSON is a Python dictionary, so you can use all functions that are valid for dictionaries.
In your case "components" is the key of the dictionary, whose value is a list. Each item in the list is an another dictionary.

Categories