Get Multiple Keys From Json In Python
Solution 1:
You need to iterate over each dictionary in the list and then index dict in turn with dict indexing. For each dictionary in the list,
- get the i dictionary
- get the value associated with
Org
in the i dictionary - print said value from (2)
In code, this is
for dict_ in jdata:
org = dict_['Org']
print(org)
However, we have the power of list comprehension at our disposal, so the code above can more succinctly be represented by,
jdata = json.loads(str_of_above_json)
orgs = [x['Org'] for x in jdata]
print(orgs)
Why isn't your current code working?
You do jdata['Org']
, but [...]
is a dict indexing operation, and this will throw errors because jdata
is a list.
Solution 2:
Remember, your data once loaded in as a Python structure is going to be a list of dictionaries. To keep it simple, it's just:
[{...}, {...}, {...}]
Keyword here is a list. So, your for loop will/should iterate over a list, giving you each dictionary at every iteration.
At this point you can then access the 'Org' key.
So when you do:
for orgs in jdata:
print(orgs) # each dictionary
At that point, you can now access the Org
key in the dictionary:
for orgs in jdata:
print(orgs) # each dictionaryprint(orgs['Org']) # The value of 'Org' in each dictionary
Solution 3:
import json
jdata = json.loads(str_of_above_json)
for orgs in jdata:
print(orgs["Org"])
You need to iterate over the list [] then print the "org" part of each data.
Solution 4:
All the other answers are correct and will solve your current problem.
But if you manipulate a lot with structures like this, you might find the package plucky
helpful (full disclosure: I'm the author of that package).
For example (assuming your jdata
is loaded):
>>> import plucky
>>> plucky.plucks(data, '.Org')
['b4256282', 'b4257482', 'b4253345']
or:
>>> plucky.pluckable(data).Org['b4256282', 'b4257482', 'b4253345']
Post a Comment for "Get Multiple Keys From Json In Python"