Home > Mobile >  Search JSON tree with Python
Search JSON tree with Python

Time:12-25

I have a JSON file that looks something like this

{
    "valid": true,
    "data": {
        "1": "AT",
        "-260": {
            "1": {
                "v": [
                    {
                        "dn": 1,
                    }
                ],
      
                "ver": "1.3.0",
            }
        }
    }
}

The letter I need to check if the json file is a and in the json is a "v" or an "r" How can i proof this. I am like this now in python, but i want to know what letter stands on the position from v

datajson = json.loads(data.decode("utf-8"))
        print(datajson["data"])

Thanks for the help...

CodePudding user response:

I think your problem is that you didn't understand how dictionary/json works.

Here is an sample code I made, hope it helps:

import json

# Loads the JSON file
with open("test.json", 'r') as freader:
    my_dict = json.load(fp=freader)

# The JSON load retrieves a dictionary that you can access by key name
print(my_dict)
print(my_dict["data"]["-260"])

# The dictionary object have a lot of usefull methods. You can retrieve all the keys within a dictionary using .keys().
print(my_dict["data"]["-260"]["1"].keys())

# Here we print the first key ignoring its name. Note that you may need to sort the keys by name otherwise you can
# have unexpected results.
print(list(my_dict["data"]["-260"]["1"].keys())[0])
# Here we use the same logic to print the first value.
print(list(my_dict["data"]["-260"]["1"].values())[0])

# Here we iterate through the keys and process its value if the keys match an 'r' or an 'v'
for key, val in my_dict["data"]["-260"]["1"].items():
    if key in ['v', 'r']:
        # do what you want here
        print(val)

Outputs:

{'valid': True, 'data': {'1': 'AT', '-260': {'1': {'v': [{'dn': 1}], 'ver': '1.3.0'}}}}
{'1': {'v': [{'dn': 1}], 'ver': '1.3.0'}}
dict_keys(['v', 'ver'])
v
[{'dn': 1}]
[{'dn': 1}]
  • Related