Find position of object by Key in json file

Question:

Is there anyway i can find the position of object by its key in Json file. I tried with the collection module but seems not to work with data from the json file even though its dictionary

reda.json file

[{"carl": "33"}, {"break": "55"}, {"user": "heake"}, ]
import json
import collections

json_data = json.load(open('reda.json'))
if type(json_data) is dict:
    json_data = [json_data]

d = collections.OrderedDict((json_data))
h = tuple(d.keys()).index('break')
print(h)


Also tried this

j = 'break'
for i in json_data:
    if j in i:
      print(j.index('break'))

Result is 0
``
Asked By: Alesia Thiel

||

Answers:

You can use enumerate to generate indices for a sequence:

json_data = [{"carl": "33"}, {"break": "55"}, {"user": "heake"}]
key = 'break'
for index, record in enumerate(json_data):
    if key in record:
        print(index)

This outputs: 1

Answered By: blhsing

You don’t require collections for this. Simply use list comprehension to generate a list and then get the index.

Here’s my code:

import json

json_data = json.load(open('reda.json'))
json_key_index = [key for key in json_data]
print(json_key_index.index("break"))

Also, looking at your reda.json the format doesn’t seem pretty well-versed. I recommend changing the reda.json to:

{
    "carl": "33", 
    "break": "55", 
    "user": "heake"
}
Answered By: The Myth
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.