>>> import json
>>> a = json.loads('{"X":"value1","Y":"value2","Z":[{"A":"value3","B":"value4"}]}')
>>> a
{'Y': 'value2', 'X': 'value1', 'Z': [{'A': 'value3', 'B': 'value4'}]}
>>> a["Z"][0]["A"]
'value3'
Answer from Tim Pietzcker on Stack Overflow>>> import json
>>> a = json.loads('{"X":"value1","Y":"value2","Z":[{"A":"value3","B":"value4"}]}')
>>> a
{'Y': 'value2', 'X': 'value1', 'Z': [{'A': 'value3', 'B': 'value4'}]}
>>> a["Z"][0]["A"]
'value3'
OK, I assume your JSON looks like this (note the " around each value):
{"X":"value1", "Y":"value2", "Z":[{"A":"value3", "B":"value4"}]}
Then you can do this:
import json
j = '{"X":"value1", "Y":"value2", "Z":[{"A":"value3", "B":"value4"}]}'
k = json.loads(j)
assert k["Z"][0]["A"] == "value3"
Edit: Even simplejsoncan't decode your original input.
>>> import simplejson
>>> s1 = '{"X":value1,"Y":"value2","Z":[{"A":"value3","B":value4}]}'
>>> simplejson.loads(s1)
simplejson.decoder.JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)
>>> s2 = '{"X":"value1", "Y":"value2", "Z":[{"A":"value3", "B":"value4"}]}'
>>> print simplejson.loads(s2)["Z"][0]["A"]
value3
Try iterating through the array that you get back from json.load:
data = json.load(data_file)
for obj in data:
pprint(obj['objectId'])
In this case json.load(data_file) should return a list of dictionaries. You can loop through each element of this list and access its dictionary keys and values. Specifically, what you are trying to do can be done as follows:
data = json.load(data_file)
for element in data: # data is a list
print element['objectId'] # element is a dictionary
I used print because 'objectId' is a string. If it were a more complex structure you should have used pprint instead.
You are using a string to index the list, '0' is a string, not an integer. Remove the quotes:
print(data['cosponsors'][0]['thomas_id'])
When in doubt, check the partial result; see what print(type(data['cosponsors'])) produces; if that produces <type 'list'>, you know you need to use indexing with integers, if you get <type 'dict'>, use keys (a list of which can be gotten by calling print(list(...)) on the dictionary), etc.
Usually, lists contain a variable number of objects; it could be just one, zero or a whole load more. You could loop over those objects:
for cosponsor in data['cosponsors']:
print(cosponsor['thomas_id'])
The loop sets cosponsor to each of the objects in the data['cosponsors'] list, one by one.
How about
data['cosponsors'][0]['thomas_id']
Since a list has numeric indices.