Loren Kociko
Loren Kociko

Reputation: 31

Python JSON get value by string path

I have a JSON file that I want to automatically check specific values, like: myJSON['generic']['lessgeneric']['store'] should be equal to 100,

I was thinking of doing something like this:

checks = [
    {'name':'field_1','path':'myJSON['generic']['lessgeneric']['store']','value':'100'}
]

I have no clue how to convert the string "myJSON['generic']['lessgeneric']['store']" into it's value.

edit: how I solved it

path = "generic>lessgeneric>store"
value = 100
def check_value(path,value):
    temp_json = my_json
    for key in path.split(">"):
        temp_json = temp_json[key]
    if temp_json == value:
        pass

Upvotes: 2

Views: 1945

Answers (1)

pho
pho

Reputation: 25489

Instead of storing the path like that, I suggest you store it as a list or as a delimited string. For example:

checks = [ {'name': 'field_1', 'path': 'generic/lessgeneric/store', 'value': 100} ]

Then, you can split the value of the path key with str.split(), and drill down into your object. The following recursive function takes an object (that we expect to be a dictionary) and a list containing all the keys to drill down into, and returns the value at the final key:

def drill_down(obj, path):
    if len(path) == 1: 
        # if path has a single element, return that key of the dict
        return obj[path[0]] 
    else:
       # Take the key given by the first element of path. Then drill down into it
       return drill_down(obj[path[0]], path[1:]) 

Then, do:

for c in checks:
    path = c['path'].split('/')
    assert drill_down(myJSON, path) == c['value']

This assumes you've already parsed your json into an object in the myJSON variable using the json module.

Upvotes: 2

Related Questions