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.
2
Answers
Your json is :
If you want to get
data1
without using index you can use for loop. this will take O(N) time:Or List comprehension:
Ideally,it should be with O(1) time
Or
There is much a simpler way.
I would do that with this technique:
Now you can directly access data1 and data2
And the output will be
123.45