Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find position of object by Key in json file

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
``

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading