Here is a sample JSON output myJSON:
{ "results": [
{
"data1": 123.45,
"data2": 67.89
}
]
}
I’m trying to directly read data1:
mydata1 = myJSON['data1']
I get an error KeyError: 'data1'. I can only find a way to do this by using an index:
mydata1 = myJSON['results'][0]['data1']
Is there a way to directly read the value in data1 without having to specify an index for results? Or is an index required? Just trying to find a more compact / elegant solution here.
>Solution :
Your json is :
myJSON = {
"results": [
{
"data1": 123.45,
"data2": 67.89
}
]
}
If you want to get data1 without using index you can use for loop. this will take O(N) time:
for x in myJSON["results"]:
mydata1 = x['data1']
print(mydata1)
#123.45
Or List comprehension:
mydata1 = [x['data1'] for x in myJSON["results"]]
print(*mydata1)
#123.45
Ideally,it should be with O(1) time
mydata1 = myJSON['results'][0]['data1']
Or
mydata1 = myJSON['results'][-1]['data1']