在我的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'}
总是乐于提供帮助!