S.Slusky
S.Slusky

Reputation: 242

Best Match Search Json File

I have a json file with something like this:

{
"Cars": [
 {
  "name": 'Honda'
  "color": 'Black'
  "age": 'Old'
  },
 {
  "name": 'Ford'
  "color": ' Red'
  "age": 'Old'
  },
 {
  "name": 'Mazda'
  "color": 'Black'
  "age": 'New'
  }
 ]
}

I want to write a function that will prompt the user to provide a name, color, and age, and then it will search through the json and return the objects that best match the search parameters. I also want the user to be able to only enter some of the parameters.

Examples:

I can't think of any programmatic ways to do this that aren't incredibly inefficient. The best thing I can think of is basically searching the whole Json for match's to the first key, then searching those for matches of the second key, then searching those for matches of the third key, then printing the resultant. Skipping keys that dont exist in the query payload would help, but that still seems really inefficient.

I'm not sure if I'm allowed to ask technique questions on here, so if the answer is that I should go build said inefficient function and then come back for info on how to improve it, that's fine, but I thought I might as well ask if there were any common examples first.

Upvotes: 0

Views: 339

Answers (1)

sourav sankpal
sourav sankpal

Reputation: 47

#lets say your json is stored in variable json_var
car_name=input("car name")
car_color=input("car color")
car_age=input("car_age")

car_list=[]
for cars in json_var["cars"]:
    if (cars["name"]==car_name or cars["color"]==car_color or cars["age"]==car_age):
        car_list.append(cars["name"])

print(car_list)
 

Upvotes: 2

Related Questions