Python Accessing Nested JSON Data
I did not realize that the first nested element is actually an array. The correct way access to the post code key is as follows:
r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()
print j['state']
print j['places'][1]['post code']
Best way to navigate a nested JSON in Python?
You simply iterate over the values of the dictionary, check whether the value of the 'key' item is in your list and if that's the case, append the value of the 'name' item to your output list.
Let jsonObj
be your JSON object presented in your question. Then this code should work:
listOfNumbers = [266, 166, 123, 283]
names = []
for value in jsonObj['data'].values():
if value['key'] in listOfNumbers:
names.append(value['name'])
JSON objects in Python are just dictionaries. So, you better familiarize yourself with Python's dict
.
Accessing nested JSON elements in Python
You simply need to access each dictionary along the way. Like this:
myvar = jsonvar['sleep'][0]['isMainSleep']
You access the list associated with the key sleep
, then its first element, which is a dictionary. Finally the value associated with the key isMainSleep
.
Note that you do not need to add the prefix 'u' in front of your keys.
In answer to your comment, you could output this as a json like this:
print json.dumps(myvar)
Access nested JSON values using Python
item['data']['values']
is a list. You need to get its first element and only then access its 'value'
field. That is, the corresponding line should be:
value = item['data']['values'][0]['value']
Check value of nested json key
Building on @TheFlyingObject's answer, the date
key you are trying to retrieve is nested inside the dictionary.
In order to access it, you need to first get the key it is stored in (that is the prices
key which holds a list) and then iterate over the objects in that list.
For example:
for i in dictionary['prices']:
if i['date'] is str(date):
print(date, 'is in the dict')
return True
# we finished going over the list inside the prices key, and didn't find the date we were looking for
print(date, 'is not in the dict')
return False
Accessing nested JSON using python
You can try:
a["Envelope"]["Body"]["GetCTProductsResponse"]["GetCTProductsResult"]["CTPRODUCT"][0]["CODE"]
Get nested JSON object safely
The canonical way to handle this in Python is to use try...except
and catch the specific error, in this case a KeyError
. If there is a possibility you will also be indexing into a list, you can also catch the IndexError
.
For example:
d = {
"obj1" : {
"obj2" : [1, 2, 3]
}
}
# Good keys
try:
l = d['obj1']['obj2']
except KeyError:
l = None
print(l)
# [1, 2, 3]
# Bad Keys
try:
l = d['obj10']['obj100']
except KeyError:
l = None
print(l)
# None
# Bad Index
try:
l = d['obj1']['obj2'][20]
except (KeyError, IndexError):
l = None
print(l)
# None
This is a pattern often called EAFP
Easier to ask for forgiveness than permission.
Related Topics
Check If a Number Is Int or Float
How to List Pip Dependencies/Requirements
Websocket VS Rest API for Real Time Data
Parameter Substitution for a SQLite "In" Clause
Matplotlib and Ipython-Notebook: Displaying Exactly the Figure That Will Be Saved
How to Detect the Python Version at Runtime
Python: the _Imagingft C Module Is Not Installed
How to Point Easy_Install to Vcvarsall.Bat
How Does This Input Work with the Python 'Any' Function
Plot a Histogram Such That Bar Heights Sum to 1 (Probability)
Number of Days Between 2 Dates, Excluding Weekends
Matplotlib Axes.Plot() VS Pyplot.Plot()
Why Not Generate the Secret Key Every Time Flask Starts
Django Datetime Issues (Default=Datetime.Now())
Merge Multiple Column Values into One Column in Python Pandas
Generate All Permutations of a List Without Adjacent Equal Elements