Reputation: 911
I need help on how do I use python to access element from JSON structure.
Assuming I have a JSON like this
{
'result':
[
{
'aa':1,
'bb':2
},
{
'cc':3,
'dd':4
}
]
}
In python, how exactly to get the data for aa
or dd
?
I tried with
str1 = {'result':[{'aa':1, 'bb':2},{'cc':3, 'dd':4}]}
str1new = str1['result']['aa]
but it gives me error
list indices must be integers, not str
How do I solve this? Is there any other method using python to get the data from JSON? Thank you for the help. I really appreciated it.
Upvotes: 3
Views: 23837
Reputation: 1975
For Python3, using the Json library you can easily parse Json.
# import statement
import json
# using example sting from above
jsonString = '{ "result" : [{ "aa": 1,"bb": 2 }, { "cc": 3, "dd": 4 }]}'
# parse json string
parsedJsonObject = json.loads(jsonString)
# access a specific property in the json object
resultObject = parsedJsonObject['result']
Upvotes: 0
Reputation: 11560
In python if you write:
str1 = {'result':[{'aa':1, 'bb':2},{'cc':3, 'dd':4}]}
it's dictionary and not json.
if your input is having json string you need to use
import json
json_str = """{
"result":
[
{
"aa":1,
"bb":2
},
{
"cc":3,
"dd":4
}
]
}"""
str1 = json.loads(json_str)
then you can use similar to python dictionary.
as answered by others you can then use
aa = str1['result'][0]['aa']
Upvotes: 2
Reputation: 27533
Try this and for the next ones use indexes like 1 or 2 if you have more, or you can loop if you have multiple indexes within the json
.
str1new = str1['result'][0]['aa']
Upvotes: 6
Reputation: 746
In Python, unless you're using a package (then specify it), "JSON" structure are actually dicts.
{
'result':
[
{
'aa':1,
'bb':2
},
{
'cc':3,
'dd':4
}
]
}
Here, your dict has only one key : result
. Its values are contained in a list. This list is a list of dicts. So use cascade index access to get your aa
value :
str1['result'][0]['aa']
Upvotes: 1
Reputation: 1420
result
is a list, so you need to reference a valid index before accessing aa
:
str1 = {'result':[{'aa':1, 'bb':2},{'cc':3, 'dd':4}]}
str1new = str1['result'][0]['aa']
Upvotes: 1
Reputation: 1493
As str1['result']
is a list, that's why you're getting list indices must be integers, not str
error.
aa = str1['result'][0]['aa']
dd = str1['result'][1]['dd']
Upvotes: 1