[英]How to find and replace a part of a value in json file
我有一个json文件,正在python中用作Dictionary。 json文件真的很长,有10k +条记录。 我需要用“ id”的值替换“ iscategorical”中的$ home部分。 进行更改后,我想保存此文件,以便可以再次将其用作字典。 感谢您的帮助。 这是一个示例:
{
"maps": [
{
"id": "xyzp",
"iscategorical": "/u/$home/app/home"
},
{
"id": "trtn",
"iscategorical": "/u/app/$home/user"
}
]}
我了解您能够成功加载文件,并且您要做的就是替换字符串并将结构再次保存到文件中。
为此,我们可以遍历数据中的字典列表,并通过使用item['id']
的值替换$home
来修改item['iscategorical']
的值。
然后,我们可以将修改后的结构转储回(新的)json文件。
import json
with open('data.json') as f:
data = json.load(f)
for item in data['maps']:
item['iscategorical'] = item['iscategorical'].replace('$home', item['id'])
with open('new_data.json', 'w') as f:
json.dump(data, f)
您的问题似乎类似于- 从JSON文件解析值? 。 但是,对于您的情况,以下代码段应该有效。
import json
with open('idata.json') as infile:
data = json.load(infile)
for elem in data["maps"]:
elem['iscategorical']=elem['iscategorical'].replace('$home',elem['id'])
with open('odata.json', 'w') as outfile:
json.dump(data, outfile)
如果是文件,您可以做的一件事是将文件加载到其中并逐行读取。
对于每行,您可以使用正则表达式查找和替换。 然后,您可以覆盖文件或写入新文件。
例如,
line.replace('$home', 'id')
另外,您可以加载json python并将其转换为字符串。 然后使用正则表达式替换文本。 最后,使用json.load()转换回Python字典。 但是10k行太长。 我认为逐行读取文件是更好的解决方案。
编辑:这是代码示例。
from tempfile import mkstemp
from shutil import move
from os import fdopen, remove
def replace(file_path, pattern, subst):
#Create temp file
fh, abs_path = mkstemp()
with fdopen(fh,'w') as new_file:
with open(file_path) as old_file:
for line in old_file:
new_file.write(line.replace(pattern, subst))
#Remove original file
remove(file_path)
#Move new file
move(abs_path, file_path)
replace('./text.txt', '$home', 'id')
“该json文件真的很长,具有10k +条记录”-尝试这种方式对大型文件应有帮助。
{ “地图”:[{ “ID”: “xyzp”, “iscategorical”: “/ U / $ HOME /应用/家”},{ “ID”: “trtn”, “iscategorical”:“/ U /应用/ $ HOME /用户“}]}
import json
with open('input.json') as f:
data = json.load(f)
my_list = []
def get_some_data():
for item in data['maps']:
yield(item['id'], item['iscategorical'])
for id, iscat in get_some_data():
temp_dict = {}
temp_dict['id'] = id
temp_dict['iscategorical'] = iscat.replace('$home', id)
my_list.append(temp_dict)
maps_dict = {}
maps_dict['maps'] = my_list
with open('output.json', 'w') as f:
json.dump(maps_dict, f)
{“ maps”:[{“ id”:“ xyzp”,“ iscategorical”:“ / u / xyzp / app / home”}},{“ id”:“ trtn”,“ iscategorical”:“ / u / app / trtn / user“}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.