Gerald McNicholl Gerald McNicholl - 3 years ago 232
Python Question

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

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?

Answer Source
jdata = json.loads(str_of_above_json)
orgs = [x['Org'] for x in jdata]      

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

A more explicit version of the list comprehension method shown above.

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download