使用python从JSON中提取多重嵌套数据
我看到过关于这个主题的其他几个问题,但即便如此,我还是无法解决这个特定案例中的问题。
在 json 文件中,我尝试从嵌套列表中获取某个整数,向其添加另一个(固定)整数,然后将修改后的整数写回到 json 文件中。我尝试修改的整数位于 json 中的嵌套列表中,如下所示:[head] –>’Creature List’ ——->value [此列表中未命名的多个条目,每个条目都括在一对花括号中] ————>’FactionID’ ———————>’value:’
我想修改“FactionID”的“值”整数(向其中添加一个固定的整数)并将结果写回到 json 文件。
有一个目录充满了 json 文件,我正尝试对其进行此操作。
我的 json 看起来像这样(我已经将其删减了很多但希望它仍然可以解析):
`{
"__data_type": "GIT ",
"AreaProperties": {
"__struct_id": 100,
"type": "struct",
"value": {
}
},
"Creature List": {
"type": "list",
"value": [
{
"__struct_id": 4,
"Appearance_Type": {
"type": "word",
"value": 242
},
"FactionID": {
"type": "word",
"value": 2
},
}
}
}
我无法访问 [‘Creature List’][‘value’] 中的子键。其中可能有几个不同的子列表。在我看来,由于 [‘Creature List’][‘value’] 下的子列表没有整数或字符串名称来标识条目,因此可能存在问题?但我无法编辑 json 来解决这个问题。
以下是我现在为了测试目的使用的代码:
for filename in os.listdir(directory):
if filename.endswith('.git.json'):
file_path = os.path.join(directory, filename)
try:
with open(file_path, 'r') as f:
data = json.load(f)
for key, value in data.items():
if key == 'Creature List' and isinstance(value, dict) and 'value' in value:
for creature in value:
if 'FactionID' in creature:
creature['FactionID']['value'] += 46
print(filename)
print(creature)
print(creature['FactionID']['value']
with open(file_path, 'w') as f:
json.dump(data, f, indent=4)
print(f"Modified {filename}")
except (json.JSONDecodeError, FileNotFoundError) as e:
print(f"Error processing {filename}: {e}")
我曾尝试使用例如 print(data[‘Creature List’][‘value’][‘FactionID’][‘value’]) 获取 FactionID“值”整数,但这会引发错误。
我对 Python 不是很熟悉,如能得到任何帮助,我将不胜感激。谢谢
1

