Python 如何在json文件中查找和替换值的一部分

Python 如何在json文件中查找和替换值的一部分,python,json,python-3.x,Python,Json,Python 3.x,我有一个json文件,在python中用作字典。 json文件非常长,包含10k+记录。我需要将“iscategorical”中的$home部分替换为“id”的值。进行更改后,我想保存此文件,以便再次将其用作词典。谢谢你的帮助。以下是一个示例: { "maps": [ { "id": "xyzp", "iscategorical": "/u/$home/app/home" }, { "id": "trtn",

我有一个json文件,在python中用作字典。 json文件非常长,包含10k+记录。我需要将“iscategorical”中的$home部分替换为“id”的值。进行更改后,我想保存此文件,以便再次将其用作词典。谢谢你的帮助。以下是一个示例:

{
"maps": [
    {
        "id": "xyzp",
        "iscategorical": "/u/$home/app/home"
    },
    {
        "id": "trtn",
        "iscategorical": "/u/app/$home/user"
    }
]}

如果它是一个文件,您可以做的一件事就是加载该文件并逐行读取

对于everyline,可以使用正则表达式查找和替换。然后,您可以覆盖该文件或写入新文件

比如说,

line.replace('$home', 'id')
或者,您可以在python中加载json并将其转换为字符串。然后使用正则表达式替换文本。最后,使用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')

据我所知,您能够成功加载该文件,您所要做的就是替换字符串并再次将结构保存到文件中

为此,我们可以遍历数据中的词典列表,并通过将
$home
替换为
项['id']
来修改
项['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)

你的问题似乎类似于-。 不过,对于您的情况,下面的代码段应该可以工作

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)
“json文件非常长,包含10k+记录”-尝试这种方式,对于大型文件应该会有所帮助

  • input.json
{“映射”:[{“id”:“xyzp”,“iscategorical”:“/u/$home/app/home”},{“id”:“trtn”,“iscategorical”:“/u/app/$home/user”}

  • output.json:

{“maps”:[{“id”:“xyzp”,“iscategorical”:“/u/xyzp/app/home”},{“id”:“trtn”,“iscategorical”:“/u/app/trtn/user”}]}

是否
“id:
总是在
“iscategorical”:
键之前?当您说您将给定的json文件用作字典时,在我看来,它加载时没有问题。如果是这样,您应该能够遍历字典列表,执行替换,并将其重新转储到文件中。让我看看是否可以为此编写解决方案。@tripleee“id”并不总是在“iscategorical”键之前。在这两者之间可能会有其他的键。这很有效,但我不得不尝试一下。谢谢你的帮助!很乐意帮忙。干杯
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)