通过python添加多个json字段

2024-09-29 21:36:02 发布

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

我有一个json文件,比如:

{
  "parentNode": {
    "id": "root",
    "mbs": [
      16995.9859862176,
      -6029.919928079834,
      -4.6344976928710935,
      4674.872691701428
    ]
  },
  "children": [
    {
      "id": "00t2",
      "mbs": [
        16561.761031809023,
        -5189.992543469676,
        5,
        221.7414398051216
      ]
    },
    {
      "id": "01t2",
      "mbs": [
        16851.244334748077,
        -5189.992543469676,
        5,
        221.7414398051216
      ]
    }
  ]
}

现在我想更改mbs值,但是在回滚之前需要一个日志。你知道吗

所以我的代码是:

if jsondict['parentNode']:
    mbsx=jsondict['parentNode']['mbs'][0]
    mbsy=jsondict['parentNode']['mbs'][1]
    nodeid=jsondict['parentNode']['id']  #log the node id and mbs value

    jsondict['mymbs_parent']=[nodeid,mbsx,mbsy]  #write em down

    jsondict['parentNode']['mbs'][0]=mbsx+xoffset  #then change the value
    jsondict['parentNode']['mbs'][1]=mbsy+yoffset

这对父节点很好

但是可能有许多子节点,因此对于子节点部分,代码如下所示:

if jsondict['children']:
    count=len(jsondict['children'])
    for i in range(count):
        mbsx=jsondict['children'][i]['mbs'][0]
        mbsy=jsondict['children'][i]['mbs'][1]
        nodeid=jsondict['children'][i]['id']
        jsondict['mymbs_children'][i]=(nodeid,mbsx,mbsy)
        jsondict['children'][i]['mbs'][0]=mbsx+xoffset
        jsondict['children'][i]['mbs'][1]=mbsy+yoffset

然后我得到list assignment index out of range错误。你知道吗

我想json文件中还没有mymbs_children,所以没有jsondict['mymbs_children'][i]

我还不知道怎么做,有什么想法吗?你知道吗


Tags: 文件the代码idjsonif节点children
3条回答

您可以在if循环周围放置一个for条件来检查:

  ...
  if count > 0:
    for i in range(count):
      ...

对于python3.8以后的版本,还可以使用walrus操作符来减少代码行数:(for more info

  ...
  if (count := len(jsondict['children'])) > 0:
    for i in range(count):
      ...

我更喜欢的另一种方式是不使用range

...
    for child in jsondict['children']:
      child['mbs'][blah]...
...

这将避免超出范围索引的问题,您甚至可能不需要使用count变量

# Key "mymbs_children" is not present in the dictionary yet,
# so you'll need to declare it first and initialise to an empty list.
jsondict['mymbs_children'] = []
if jsondict['children']:
    count=len(jsondict['children'])
    for i in range(count):
        mbsx=jsondict['children'][i]['mbs'][0]
        mbsy=jsondict['children'][i]['mbs'][1]
        nodeid=jsondict['children'][i]['id']
        # Use append to add the tuple to this list
        jsondict['mymbs_children'].append((nodeid,mbsx,mbsy));

我不喜欢你的方法,但为了简单起见,我可以回答你提出的问题。若要修复出现的错误,请添加

    jsondict['mymbs_children'] = []

作为后面的第一行

if jsondict['children']:

这将创建一个列表,然后您将尝试写入该列表。你知道吗

然后需要使用.append()将项目添加到列表中:

jsondict['mymbs_children'].append((nodeid,mbsx,mbsy))

而不是

jsondict['mymbs_children'][i]=(nodeid,mbsx,mbsy)

相关问题 更多 >

    热门问题