[英]Python Search and replace in a json text file
how do i replace number inside "id": "1",
and increment the number by +1 also remove the quotes around the number "id": 1
should look like this.我如何替换
"id": "1",
并将数字增加+1,同时删除数字"id": 1
周围的引号"id": 1
应该是这样的。
Here is an example of the json file, but it's huge.这是 json 文件的示例,但它很大。 So doing this automatic by python would save alot of time
因此,通过python自动执行此操作将节省大量时间
[
{
"id": "1",
"text": "How old can a sea turtle get?",
},
{
"id": "2",
"text": "How many fishes are in the lake?",
}
]
This is how far i got:这是我有多远:
import re
with open("new 2.txt") as file:
for line in file.readlines():
x = re.findall('"id": "[a-zA-z]{0,1}[0-9]*"', line)
Use the json
module, not regex.使用
json
模块,而不是正则表达式。
import json
with open('new.txt') as f:
records = json.load(f)
for item in records:
item['id'] = int(item['id']) + 1
with open('updated.txt') as f:
json.dump(records, f, indent=4)
Et voila:等等:
[
{
"id": 2,
"text": "How old can a sea turtle get?"
},
{
"id": 3,
"text": "How many fishes are in the lake?"
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.