【问题标题】:error in json python parsingjson python解析中的错误
【发布时间】:2015-03-25 22:02:34
【问题描述】:

我已经加载了一个 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: list indices must be integers, not str”。

如何检索节点以及如何更新它?

【问题讨论】:

  • 顺便说一句,您拥有的 JSON 已损坏,倒数第三行在 } 之后有一个 ,,它不应该存在。
  • 谢谢,是我的错,幸好只是复制粘贴不好,原来的JSON没问题。

标签: python json parsing dictionary


【解决方案1】:

在您的 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

【讨论】:

  • 谢谢约瑟夫,但是这样我如何向旧节点添加新值? (比如说...我需要在 id = 'node5' 的节点中添加“z”= 12。)
  • 如果您对正在读取的 JSON 没有任何控制权,您有两种选择:一种,遍历所有 json['nodes'] 并在循环内检查当前元素是否为您要修改的那个。或者,更好的是,只需根据其内容将 jsonData['nodes'] 转换为 dict 本身,例如 jsonData['nodes'] = {e['id']: e for e in jsonData['nodes']}
  • 谢谢约瑟夫。我试试看。
  • 太棒了。如果可行,请务必通过单击左侧的复选标记将此答案标记为“已接受”。
【解决方案2】:

这个sn-p给一个老节点增加一个新值(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

【讨论】:

    猜你喜欢
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多