【问题标题】:How to iterate through JSON dictonary with Python如何使用 Python 遍历 JSON 字典
【发布时间】:2020-10-22 12:19:13
【问题描述】:

我的代码是这样的


    with open('base.json') as f:
        data = json.load(f)

    for Object in data["Objects"][0]:
        print(Object["Name"])  

我正在尝试能够打印

SellMenu
BuyMenu

所以我可以向特定菜单添加按钮,但此代码不起作用并且崩溃 我的 JSON(base.json) 是

{
    "Objects": [
    {
        "Type": "Menu",
        "Path": "insert_path",
        "Name": "SellMenu",
        "X": 0,
        "Y": 0,
        "Width": 1920,
        "Height": 1080,
        "Buttons": [],
        "Text": []
    },
    {
        "Type": "Menu",
        "Path": "insert_path",
        "Name": "BuyMenu",
        "X": 0,
        "Y": 0,
        "Width": 1920,
        "Height": 1080,
        "Buttons": [],
        "Text": []
    }]
}

【问题讨论】:

  • data["Objects"][0]中删除[0]

标签: python json python-3.x loops parsing


【解决方案1】:

试试这个:

for Object in data["Objects"]:
    print(Object["Name"])  

说明:

通过这样做for Object in data["Objects"][0]:,实际上你试图迭代列表中的第一个元素。 为了迭代列表本身,您必须编写for Object in data["Objects"]:。确实,data["Objects"] 的类型是列表。

【讨论】:

  • @KyleKip 你确定吗?这个对我有用。你得到什么结果/错误?
  • @ThunderPhenix 如果我尝试使用 data["Objects"][0]["Buttons"].append 添加到第二个字典中,我该怎么做?现在它只是添加到第一个
  • @KyleKip 我不明白你的问题。尽量明确。
  • 好的,所以我有 2 个菜单,一个 SellMenuBuyMenu 都有一个 Buttons[] 在我的 python 代码中,我使用这一行附加到 JSON 文件 data["Objects"][0]["Buttons"].append({"RX": ButtonObject.x, "RY": ButtonObject.y, "Width": ButtonObject.width, "Height" : ButtonObject.height, "Path": ButtonObject.path, "Name" : ButtonObject.name})称之为它添加到它发现的第一个Buttons[] 不是正确的。如何指定使用哪一个。不知道如何告诉它去BuyMenuSellMenu
  • @KyleKip 将data["Objects"][0]... 用于SellMenudata["Objects"][1] ... 用于BuyMenu
【解决方案2】:

在我的test.json 文件中使用与您发布的相同的内容,此功能目前按要求执行。现在我只想指出Object是python中的保留关键字,这可能会导致这里发生冲突:

def jsonTest():
    import json
    with open('test.json', 'r') as f:
        data = json.load(f)
    for element in data['Objects']:
        print(element['Name'])

jsonTest()

输出:

> python .\testing.py
SellMenu
BuyMenu

通过使用 data['Objects'][0] 列表的第零个索引,您要求迭代器循环以下内容:

    for element in data['Objects'][0]:
        print(f'Element: {element:8s} <==> Type: {type(element)}')

您可以从输出中看到它不是字典的key,而是一个字符串。 输出:

> python .\testing.py
Element: Type     <==> Type: <class 'str'>
Element: Path     <==> Type: <class 'str'>
Element: Name     <==> Type: <class 'str'>
Element: X        <==> Type: <class 'str'>
Element: Y        <==> Type: <class 'str'>
Element: Width    <==> Type: <class 'str'>
Element: Height   <==> Type: <class 'str'>
Element: Buttons  <==> Type: <class 'str'>
Element: Text     <==> Type: <class 'str'>

因此您需要遍历data['Objects'] 列表。

for element in data['Objects']:
        print(f'Type: {type(element)}\nDict: {element}')

输出:

> python .\testing.py
Type: <class 'dict'>
Dict: {'Type': 'Menu', 'Path': 'insert_path', 'Name': 'SellMenu', 'X': 0, 'Y': 0, 'Width': 1920, 'Height': 1080, 'Buttons': [], 'Text': []}
Type: <class 'dict'>
Dict: {'Type': 'Menu', 'Path': 'insert_path', 'Name': 'BuyMenu', 'X': 0, 'Y': 0, 'Width': 1920, 'Height': 1080, 'Buttons': [], 'Text': []}

这将使您可以访问正常的字典操作。希望这是有道理的。

编辑: 为了将字典附加到字典的末尾,您可以通过使用某种形式的 for 循环来单独添加每个元素,或者您可以使用字典的 extend 方法,如下所示:

data['Objects'][0]['Buttons'].extend({"RX": ButtonObject.x, "RY": ButtonObject.y, "Width": ButtonObject.width, "Height" : ButtonObject.height, "Name" : ButtonObject.name}).extend({"RX": ButtonObject.x, "RY": ButtonObject.y, "Width": ButtonObject.width, "Height" : ButtonObject.height, "Name" : ButtonObject.name})

这里的问题是,默认情况下 ['Buttons'] 是一个列表 [] 而不是字典 {},因此使用动态类型您可以通过将其分配给新的类型来重新键入(重新声明类型)类型(=): 输出:

>>> d = {'Type': 'Menu', 'Path': 'insert_path', 'Name': 'SellMenu', 'X': 0, 'Y': 0, 'Width': 1920, 'Height': 1080, 'Buttons': [], 'Text': []}
>>> d['Buttons']
[]

>>> d['Buttons'] = {"RX": 123, "RY": 321, "Width": 10, "Height" : 73, "Name" : 'Robin'}
>>> d['Buttons']
{'RX': 123, 'RY': 321, 'Width': 10, 'Height': 73, 'Name': 'Robin'}

总是乐于提供帮助!

【讨论】:

  • 哦,这很有道理,谢谢!快速提问。如果我想在 SellMenu 或 BuyMenu 中添加 data["Objects"][0]["Buttons"].append({"RX": ButtonObject.x, "RY": ButtonObject.y, "Width": ButtonObject.width, "Height" : ButtonObject.height, "Name" : ButtonObject.name}) 之类的内容,我该如何明确地说出来?
猜你喜欢
  • 1970-01-01
  • 2018-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 2017-05-23
  • 2017-01-18
相关资源
最近更新 更多