Places is a list and not a dictionary. This line below should therefore not work:
print(data['places']['latitude'])
You need to select one of the items in places and then you can list the place's properties. So to get the first post code you'd do:
print(data['places'][0]['post code'])
Answer from agrinh on Stack OverflowPlaces is a list and not a dictionary. This line below should therefore not work:
print(data['places']['latitude'])
You need to select one of the items in places and then you can list the place's properties. So to get the first post code you'd do:
print(data['places'][0]['post code'])
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']
Videos
Hello. I wrote a straightforward library to extract values from JSON data key:values once it is a python object (list or dict) via json.loads().
jsonparse github
I initially made this to practice dfs/bfs. I have since cleaned it up a bunch, documented it, created tests, etc. and I'm happy to show off.
Use-case: I use this to find values via key(s) or key:value pairs in deeply nested JSON data from API's.
Examples in the README.md
I'm happy for any feedback that you are willing to share!
It is a bit lenghty, but in that example above:
In [1]: import json
In [2]: s = """\
...: {
...: "A": {
...: "B": {
...: "unknown": {
...: "1": "F",
...: "maindata": [
...: {
...: "Info": "TEXT"
...: }
...: ]
...: }
...: }
...: }
...: }"""
In [3]: data = json.loads(s)
In [4]: data['A']['B']['unknown']['maindata'][0]['Info']
Out[4]: u'TEXT'
You basically treat it as a dictionary, passing the keys to get the values of each nested dictionary. The only different part is when you hit maindata, where the resulting value is a list. In order to handle that, we pull the first element [0] and then access the Info key to get the value TEXT.
In the case of unknown changing, you would replace it with a variable that represents the 'known' name it will take at that point in your code:
my_variable = 'some_name'
data['A']['B'][my_variable]['maindata'][0]['Info']
And if I would have actually read your question properly the first time, if you don't know what unknown is at any point, you can do something like this:
data['A']['B'].values()[0]['maindata'][0]['Info']
Where values() is a variable containing:
[{u'1': u'F', u'maindata': [{u'Info': u'TEXT'}]}]
A single-item list that can be accessed with [0] and then you can proceed as above. Note that this is dependent on there only being one item present in that dictionary - you would need to adjust a bit if there were more.
You can use a recursive function to dig through every layer and print its value with an indent
def recurse_keys(df, indent = ' '):
'''
import json, requests, pandas
r = requests.post(...)
rj = r.json() # json decode results query
j = json.dumps(rj, sort_keys=True,indent=2)
df1 = pandas.read_json(j)
'''
for key in df.keys():
print(indent+str(key))
if isinstance(df[key], dict):
recurse_keys(df[key], indent+' ')
recurse_keys(df1)
I have the following json structure file:
parent1 -------subcat1 ----------------subsubcat1 ----------------.... ----------------subsubcatN -------.... -------subcatN parent2 -------subcat1 ----------------subsubcat1 ----------------.... ----------------subsubcatN -------.... -------subcatN
and each subsubcat has list of dictionaries in which one key - value pair can be 'uid':'12563'.
I need to check if parent1, parent2 has this par, or none of them... problem i subcat and subsubcat keys are not consistent (they change depending on json file), deepness stays the same.
Basically i need smng like
if json['parent1][*][*][*]['uid'] == 12563
but it's not gonna work :)