Python – 替换 JSON 主体中的整数

huangapple go评论79阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月6日 00:48:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76408485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定