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

Viewed 932

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?

3 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')

Python Dictionaries are Unordered. It means you can't access the dictionary element based on its index value. You need to provide key to access the corresponding value or values.

Is this what you are looking for?

You can get the term inside the JSON by specifying the Key value of the data. Here, eee is the Key:

print((data['eee']))

which will print:

yes

similarly you can use other Key to get their respective values.

The JSON data is formatted as Key:Value

Related