Python读取JSON文件并修改 [英] Python read JSON file and modify
本文介绍了Python读取JSON文件并修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我正在尝试从一个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'] = ...
>。
导入json
打开('data.json','r +')as f:
data = json.load(f)
data ['id'] = 134#< --- add`id` value。
f.seek(0)#< ---应将文件位置重置为开头。
json.dump(data,f,indent = 4)
f.truncate()#删除剩余部分
Hi I am trying to take the data from a json file and insert and id then perform POST REST. my file data.json has:
{
'name':'myname'
}
and I would like to add an id so that the json data looks like:
{
'id': 134,
'name': 'myname'
}
So I tried:
import json
f = open("data.json","r")
data = f.read()
jsonObj = json.loads(data)
I can't get to load the json format file. What should I do so that I can convert the json file into json object and add another id value.
解决方案
Set item using 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文件并修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文