2

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
1
  • If you have control over things, a list of keys would be much safer to use. If what you ultimatley want to do is validate your json then I would look at : stackoverflow.com/questions/54491156/… Commented Mar 23, 2022 at 19:24

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.