3

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?

2
  • Indexing requires a list. Commented Jan 14, 2021 at 22:30
  • the reason you are getting KeyError is because you do not have 0 as key in your dictionary Commented Jan 14, 2021 at 22:46

3 Answers 3

1

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')
Sign up to request clarification or add additional context in comments.

1 Comment

While the latest versions of Python maintain dict key insertion order, it is not guaranteed in older versions. The C implementation of Python 3.6 first maintained key order as an implementation detail, and order is standard in Python 3.7. Don't expect other implementations of 3.6 and any implementation of 3.5 and older to return 'eee' for item[0].
1

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.

1 Comment

Python dictionaries as of 3.7 maintain insertion order. While they can't be indexed, they can be iterated.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.