Skip to content
Advertisement

Accessing Json object values with the Help of a dictionary

I’ve a huge json file which has a lot of nested key value pairs. So I thought I should save the keys as dictionary values and use that dictionary values as keys to access the values from the json file. Say for example:

json_obj = {
 "calendar" :{
    "day": {
      "activities" : {
         "morning:"walk"
       }
     }
  }
}

so I thought to access the key morning value, instead of writing

json_obj['calendar']['day']['activities']['morning']

I should keep a dictionary which will contain the query parameters like

query_parameters = {
 0 :[['calendar'],['day'],['activities'],['morning']]
}

And use this dictionary to query from the json object.
But

Here is my question?
Can I use this dictionary to write query or to access values from my json_obj without using any loops ?
say something like json_obj[query_parameters[0]] # this is not right syntax I know
Or do you have any suggestions when accessing these long key value pair from an object?

Advertisement

Answer

You can write a function like this This function will return value if exist otherwise returns None

def fun(query, data):
    if not query:
        return data
    if query[0][0] in data:
        return fun(query[1:], data[query[0][0]])

print(fun(query_parameters[0], json_obj)) # walk
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement