您好,我正在尝试从 json 文件中获取数据并插入和 id,然后执行 POST REST。 我的文件 data.json 有:
{
'name':'myname'
}
我想添加一个 id 以便 json 数据看起来像:
{
'id': 134,
'name': 'myname'
}
所以我尝试了:
import json
f = open("data.json","r")
data = f.read()
jsonObj = json.loads(data)
我无法加载 json 格式文件。 我应该怎么做才能将 json 文件转换为 json 对象并添加另一个 id 值。
最佳答案
使用 data['id'] = ...
设置项目。
import json
with open('data.json', 'r+') as f:
data = json.load(f)
data['id'] = 134 # <--- add `id` value.
f.seek(0) # <--- should reset file position to the beginning.
json.dump(data, f, indent=4)
f.truncate() # remove remaining part
关于Python读取JSON文件并修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21035762/