json python解析时出错

2024-09-27 21:33:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经加载了一个JSON文件,但无法解析它来更新或插入值。你知道吗

JSON结构与此类似:

{
    "nodes": [
        {
            "id": "node1",
            "x": 21.0,
            "y": 8.0
        },
        {
            "id": "node5",
            "x": 3.0,
            "y": 5.0
        }
    ]
}

虽然我检索节点的python代码类似于:

jsonData = defaultdict(list)
with open('data.json', 'r') as f:
    jsonData = json.load(f)
print jsonData['nodes']['id'] == 'node5'

我得到的错误是“TypeError:列表索引必须是整数,而不是str”。你知道吗

如何检索节点以及如何更新节点?你知道吗


Tags: 文件代码idjson节点withopen结构
2条回答

此代码段向旧节点添加新值(z=12)并更新现有节点y

import json
from collections import defaultdict

jsonData = defaultdict(list)
with open('c:/temp/data.json', 'r') as f:
    jsonData = json.load(f)
for item in jsonData['nodes']:
    if  item['id']=='node5':
       item['y'] = 5
       item['z'] = 12

在JSON中,nodes是一个对象列表,因此不能像使用'id'那样使用字符串来访问其中的元素。你知道吗

相反,您可以对其进行迭代:

with open('data.json', 'r') as f:
    jsonData = json.load(f)

for item in jsonData['nodes']:
    print item['id'], item['x'], item['y']

[编辑] 针对您的评论:

with open('data.json', 'r') as f:
    jsonData = json.load(f)

jsonData['nodes'] = {e['id']: e for e in jsonData['nodes']}
jsonData['nodes']['node5']['z'] = 12

相关问题 更多 >

    热门问题