Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Value in a JSON string using a Key in Python?

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?

like image 275
David Fígols Olaria Avatar asked Aug 12 '26 05:08

David Fígols Olaria


1 Answers

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')
like image 134
azro Avatar answered Aug 13 '26 20:08

azro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!