如何在json文件中查找和替换值的一部分 [英] How to find and replace a part of a value in json file

查看:390
本文介绍了如何在json文件中查找和替换值的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json文件,我正在使用它作为python中的Dictionary. json文件真的很长,有10k +条记录.我需要用"id"的值替换"iscategorical"中的$ home部分.进行更改后,我想保存此文件,以便可以再次将其用作字典.感谢您的帮助.这是一个示例:

I have a json file that I am using as a Dictionary in python. The json file is really long with 10k+ records. I need to replace the $home part in the "iscategorical" with the value of "id". After making the changes, I want to save this file so that I can use it again as a dictionary. Thank you for the help. Here is a sample:

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

推荐答案

我了解您能够成功加载文件,而您要做的就是替换字符串并将结构再次保存到文件中.

I am understanding that you are able to load the file successfully, and all you want to do is replace the strings and save the structure to file again.

为此,我们可以遍历数据中的词典列表,并通过将$home替换为item['id']的值来修改item['iscategorical']的值.

For this, we can traverse the list of dictionaries in the data, and modify the value of item['iscategorical'] by replacing $home with the value of item['id'].

然后我们可以将修改后的结构转储回(新的)json文件中.

We can then dump the modified structure back to (a new) json file.

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文件中查找和替换值的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆