Python code:
import json
aaa='''
{
"eee":"yes",
"something": null,
"ok": ["no","mmm","eee"],
"please":false,
"no": {"f":true,"h":"ttt"}
}
'''
data=json.loads(aaa)
When I do:
print(len(data))
I get as expected:
5
and
print(len(data['ok']))
which gives
3
But somehow
print(data[0])
gives
Traceback (most recent call last):
File "file.py", line 34, in <module>
print(data[0])
KeyError: 0
How do I get a term inside this JSON object using its index?
You asked about access a position in a JSON, but the data structure is python dict, with key and values, you can index it only using it's keys as you did well with data['ok'].
To get first key, you can first get the dict.items(), which is a list of the pairs key/value, and then, as it's a list you ca index with ints
data.items()
# [('eee', 'yes'), ('something', None), ('ok', ['no', 'mmm', 'eee']), ('please', False), ('no', {'f': True, 'h': 'ttt'})]
items = list(data.items())
items[0]
# ('eee', 'yes')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With