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
``
CodePudding user response:
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
CodePudding user response:
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"
}