Here I want to find the matching json object from the json file(sample below). The provided json object which needs to be matched inside the .json
file will also have same format.
After the json object gets matched to one of them, then i want to return the previous object of that matched json object.
What is the best and fastest way to perform this with python ?
my_json_file.json
{
"all_data": [
{
"key":"value",
"key2": {
"key": "val"
}
},
{
"key":"value",
"key2": {
"key": "val"
}
},
{
"key":"value",
"key2": {
"key": "val"
}
},
]
}
get_value.py
with open('my_json.json') as file:
file_data = json.load(file)
if some_json in file_data:
# return previous json
CodePudding user response:
You could use enumerate
to iterate over file_data['all_data']
:
def fct(file_path, some_json_obj):
with open(file_path) as file:
file_data = json.load(file)
for i, obj in enumerate(file_data['all_data']):
if obj == some_json_obj: # some_json_obj will have same format as i
if i == 0:
print("First object match!")
return None
else:
print(f"Matched object #{i}, returning #{i-1}")
return file_data['all_data'][i-1]
print("No match!")
return None
CodePudding user response:
Not sure what are you looking for but your code looks right to me
import json
FILENAME="my_json"
DATA_FIELD_NAME="all_data"
lost_found={}
def find(filename=FILENAME,data_field_name=DATA_FIELD_NAME,lost_object=lost_found,default=None):
with open("{filename}.json".format(filename=filename)) as raw_file:
json_file = json.load(raw_file)
data = json_file[data_field_name]
data_length=len(data)
# if the data_length less than 1 no prev exist
if data_length < 1:
raise Exception("No data")
else:
previous_data_element = data[0]
result=default
for data_element in data:
if data_element == lost_found:
result= previous_data_element
break
previous_data_element= data_element
return result