我正在尝试使用 Python 遍历 JSON 文件并返回对象名称和相关模块。
现在我基本上可以得到我想要对索引进行硬编码的输出。但是,这显然不是正确的方法(JSON 文件的长度可能会有所不同)。
每当我尝试使用循环时,我都会收到如下错误:
TypeError: string indices must be integers
我的 JSON 文件如下所示:
{
"name": "gaming_companies",
"columns": [{
"name": "publisher",
"type": "string",
"cleansing": ["clean_string"]
},
{
"name": "genre",
"type": "string",
"cleansing": ["match_genre", "clean_string"]
},
{
"name": "sales",
"type": "int",
"cleansing": []
}
]
}
我正在“工作”的 Python 代码如下所示:
import json as js
def cleansing(games_json):
print (games_json['columns'][0]['name'] + " - cleansing:")
[print(i) for i in games_json['columns'][0]['cleansing'] ]
print (games_json['columns'][1]['name'] + " - cleansing:")
[print(i) for i in games_json['columns'][1]['cleansing'] ]
print (games_json['columns'][2]['name'] + " - cleansing:")
[print(i) for i in games_json['columns'][2]['cleansing'] ]
with open(r'C:\Desktop\gamefolder\jsonfiles\games.json') as input_json:
games_json = js.load(input_json)
cleansing(games_json)
我试图返回的输出是:
publisher
cleansing:
clean_string
genre
cleansing:
match_genre
clean_string
sales
cleansing:
我尝试像这样遍历它们:
for x in games_json:
for y in games_json['columns'][x]:
print (y)
结果:
TypeError: list indices must be integers or slices, not str
games_json 显示为字典。
列显示为字典列表。
每个对象的清理属性显示为列表。
我认为这是我的问题所在,但我无法越过障碍。
最佳答案
您尝试的问题是将迭代器用作字符串。
for y in games_json['columns'][x]:
中的 x
是一个迭代器对象,而不是字符串 ['name', '清洁']
。
您可以了解有关 python 迭代器的更多信息 here
至于这种情况 - 您可能希望将列
作为单独的列表进行迭代。
这段代码应该可以工作
for item in f["columns"]:
print(item["name"])
print("cleansing:")
print(item["cleansing"])
输出-
publisher
cleansing:
['clean_string']
genre
cleansing:
['match_genre', 'clean_string']
sales
cleansing:
[]
关于python - 如何使用带有嵌套列表和字典的 Python 遍历 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57557186/