Python 在JSON文件中再添加一个属性
因此,我有一个生成的JSON,它看起来像(有很多JSON只是具有唯一的ID) 我试图“附加”一个新字段,但我得到一个错误Python 在JSON文件中再添加一个属性,python,json,random,Python,Json,Random,因此,我有一个生成的JSON,它看起来像(有很多JSON只是具有唯一的ID) 我试图“附加”一个新字段,但我得到一个错误 with open('data.json', 'w') as file: json.dump(write_list, file) file.close() with open('data.json', 'w') as json_file: entry = {'parentId': random.randrange(0, 487, 2)} json_f
with open('data.json', 'w') as file:
json.dump(write_list, file)
file.close()
with open('data.json', 'w') as json_file:
entry = {'parentId': random.randrange(0, 487, 2)}
json_file.append(entry, json_file)
json_file.close()
生成后,是否有办法再向其添加一个“键:值”?执行所需操作的步骤为文件:
json.dump
生成列表,但没有使用json.load
重新创建Python数据结构李>
w
模式打开文件,这将截断文件with open('data.json', 'w') as file:
json.dump(write_list, file)
#file.close() # manually closing files is unnecessary,
# when using context managers
with open('data.json', 'r') as json_file:
write_list = json.load(json_file)
entry = {'parentId': random.randrange(0, 487, 2)}
write_list.append(entry)
with open('data.json', 'w') as json_file:
json.dump(write_list, file)
在我使用Tim McNamara advice完成了这个特性之后,我找到了一种更漂亮的方法,可以向文件中的每个JSON dict添加新行
for randomID in write_list:
randomID['parentId'] = random.randrange(0, 487, 2)
with open('data.json', 'w') as file:
json.dump(write_list, file)
请在此处粘贴3-5行JSON文件。不清楚结构是什么(JSON或JSON行)。{“id”:3,“name”:“name”,“dep”:“dep”,“Title”:“Title”,“email”:“email”},{“id”:4,“name”:“name”,“dep”:“dep”:“dep”,“Title”:“Title”,“email”:“email”},{“id”:5,“name”:“name”,“dep”:“dep”,“Title”:“Title”,“email”:“email”}@上面添加了coldspeed,我想让它们看起来像{“id”:3,“name”:“name”,“dep”:“dep”,“Title”:“Title”,“email”:“email”,“parentId”:“2”}有什么错误吗?是的,可能就是这样,有很多错误
for randomID in write_list:
randomID['parentId'] = random.randrange(0, 487, 2)
with open('data.json', 'w') as file:
json.dump(write_list, file)