英文:
Python - replace integer in json body
问题
需要替换JSON主体中的整数:
file1.json
{
"id": 0,
"col_1": "some value",
"col_2": "another value"
}
我知道如何替换字符串,我会使用以下方法:
import json
with open('file1.json') as f:
data = json.load(f)
data["col_1"] = data["col_1"].replace("some value", "new value")
但是如何替换id
,例如将其替换为数字5呢?
英文:
I need to replace an integer in a json body:
file1.json
{
"id": 0,
"col_1": "some value",
"col_2": "another value"
}
I know to replace a string, I would use:
import json
with open('file1.json') as f:
data = json.load(f)
data["col_1"] = data["col_1"].replace("some value", "new value")
But how would I replace the id
, to the number 5 for example?
答案1
得分: 1
你想法正确!使用 json.load(path)
将 JSON 作为字符串加载,然后在实例中操作数据确实是最简单的方法。正如评论中所说,你可以使用 data["Column name"] = new value
来设置该值,因为一旦数据被读入 Python,它就被保存为字典。
接下来需要做的是将经过操作的数据项保存为 .json 文件,我记得你要找的函数是 json.dump
。
我在这里找到了一个相关的帖子:https://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file
英文:
You've got the right idea! Loading in the json as a string with json.load(path) and then manipulating the data in the instance is certainly the easiest way to do it. As the comments said, you can set that value with data["Column name"] = new value
since once the data is read into python it's held as a dictionary.
What you need to do then is save the manipulated data item to .json, IIRC the function you're looking for is json.dump
I found a related post here: https://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论