Gerald McNicholl
Gerald McNicholl

Reputation: 43

Get multiple keys from json in Python

I have the following json structure in a file:

[
{ "Date": "timevalue", "Org": "b4256282", "Referer": "somevalue" },
{ "Date": "timevalue", "Org": "b4257482", "Referer": "somevalue" },
{ "Date": "timevalue", "Org": "b4253345", "Referer": "somevalue" },
....
]

I want to extract all the Org's.

My code is:

import json

jdata = json.loads(str_of_above_json)
for orgs in jdata['Org']:
     print(orgs)

However this code does not work ... I get the following error messag

TypeError: list indices must be integers, not str

Can anyone let me know what I am doing wrong?

Upvotes: 1

Views: 10286

Answers (4)

cs95
cs95

Reputation: 402483

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,

  1. get the ith dictionary
  2. get the value associated with Org in the ith dictionary
  3. 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.

Upvotes: 3

randomir
randomir

Reputation: 18697

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']

Upvotes: 0

idjaw
idjaw

Reputation: 26578

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 dictionary
    print(orgs['Org']) # The value of 'Org' in each dictionary

Upvotes: 2

Jomin
Jomin

Reputation: 123

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.

Upvotes: 0

Related Questions