通过python添加多个json字段
我有一个json文件,如:通过python添加多个json字段,python,json,Python,Json,我有一个json文件,如: { "parentNode": { "id": "root", "mbs": [ 16995.9859862176, -6029.919928079834, -4.6344976928710935, 4674.872691701428 ] }, "children": [ { "id": "00t2", "mbs": [ 16561.76
{
"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值,但要在回滚之前记录日志
所以我的代码是:
如果jsondict['parentNode']:
mbsx=jsondict['parentNode']['mbs'][0]
mbsy=jsondict['parentNode']['mbs'][1]
nodeid=jsondict['parentNode']['id']#记录节点id和mbs值
jsondict['mymbs_parent']=[nodeid,mbsx,mbsy]#记下它们
jsondict['parentNode']['mbs'][0]=mbsx+xoffset#然后更改该值
jsondict['parentNode']['mbs'][1]=mbsy+yoffset
这对父节点很好
但是可能有很多子节点,所以对于子节点部分,代码如下所示:
如果jsondict['children']:
count=len(jsondict['children'])
对于范围内的i(计数):
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
然后我得到列表分配索引超出范围错误
我想json文件中还没有mymbs_children
,所以没有jsondict['mymbs_children'][I]
我还没有找到怎么做,有什么想法吗?您可以在for
循环周围设置if
条件来检查:
...
if count > 0:
for i in range(count):
...
对于Python3.8以后的版本,还可以使用walrus操作符来减少代码行数:()
我更喜欢的另一种方式是不使用范围
:
...
for child in jsondict['children']:
child['mbs'][blah]...
...
这将避免超出范围索引的问题,您甚至可能不需要使用计数变量我不喜欢您的方法,但为了简单起见,我可以回答您提出的问题。要修复您得到的错误,请添加
jsondict['mymbs_children'] = []
作为之后块中的第一行
if jsondict['children']:
这将创建您尝试写入的列表
然后需要使用.append()
将项目添加到列表中:
jsondict['mymbs_children'].append((nodeid,mbsx,mbsy))
而不是
jsondict['mymbs_children'][i]=(nodeid,mbsx,mbsy)
仅供参考,如果我删除[I],代码可以正常工作,但它只写下最后一个子节点的值。当然,您正试图直接分配给列表项。您需要使用.append()
,或者先初始化列表。我会直接更新我不知道的关于jsondict['children']`中child的回答,谢谢!
jsondict['mymbs_children'][i]=(nodeid,mbsx,mbsy)
# 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));