使用Python搜索JSON树



我有一个JSON文件,看起来像这个

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

"ver": "1.3.0",
}
}
}
}

我需要检查的字母json文件是否为a,json中是否为";v〃;或一个";r〃;我怎么能证明这一点。我现在在python中是这样的,但我想知道v 的位置上有什么字母

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

谢谢你的帮助。。。

我认为您的问题是不了解dictionary/json是如何工作的。

这是我制作的一个示例代码,希望它能有所帮助:

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)

输出:

{'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}]