【问题标题】:Search JSON tree with Python使用 Python 搜索 JSON 树
【发布时间】:2022-01-24 15:58:31
【问题描述】:

我有一个类似这样的 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"])

感谢您的帮助...

【问题讨论】:

  • 你的问题不是很清楚。请说明您正在尝试做什么,根据您提供的输入预期输出,以及原因。
  • 我说的是写“v”的位置,这个位置我想看看到底是哪个字母,也可以是“v”以外的其他字母。
  • 如果json结构一致可以看j["data"]["-260"]["1"]

标签: python json python-3.x


【解决方案1】:

我认为您的问题是您不了解字典/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}]

【讨论】:

  • 你几乎从不想/不需要在字典上调用.keys()...
  • 是的。我认为主要用途是检查字典中是否存在给定的键。
  • 绝对不是 - 为此目的始终使用yourkey in yourdict!并且要进行迭代,您需要迭代 dict 本身,因为这已经为您提供了它的键。
猜你喜欢
  • 2011-07-14
  • 1970-01-01
  • 2018-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-27
相关资源
最近更新 更多