使用jq或sed替换JSON中的属性或键 [英] Replace an attribute or key in JSON using jq or sed

查看:176
本文介绍了使用jq或sed替换JSON中的属性或键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个像这样的大json

Have a big json like this

"envConfig": {
    "environmentName": {
        "versions": [
            {
                "name": "version1",
                "value": "Dev"
            },
            {
                "name": "version2",
                "host": "qa"
            }
        ],
        "userRoles": [
            {
                "name": "Roles",
                "entry": [
                    {
                        "name": "employees",
                        "value": "rwx"
                    },
                    {
                        "name": "customers",
                        "value": "rx"
                    }
                ]
            }
        ]
    }
},

我想将JSON属性从"environmentName"更改为"prod".以下是我期望的输出

I wanted to change the JSON attribute from "environmentName" to "prod". Below is the output i am expecting

"envConfig": {
    "prod": {
        "versions": [
        ...
        ],
        "userRoles": [
        ...
        ]
    }
}

尝试使用sed命令,如下所示

Tried with sed command as below

sed "s/\('environmentName':\)/\1\"prod\"\,/g" version.json

尝试使用jq进行以下操作,但不起作用

Tried with jq as below but not working

cat version.json | jq  ' with_entries(.value |=   {"prod" : .environmentName} ) '

这里的任何帮助都可以将json的属性/键替换为所需的值

Any help here to replace the attribute/key of an json with desired value

推荐答案

您与jq的差距并不大,怎么办?

You weren't too far off with the jq, how about this?

jq '.envConfig |= with_entries(.key |= sub("^environmentName$"; "prod"))'

两个区别:首先,我们想在做with_entries之前向下钻到envConfig,其次,当我们到达那里时,我们想要的东西将是键,而不是值.如果除environmentName之外还有其他键,则将保留它们.

Two differences: first off, we want to drill down to envConfig before doing a with_entries, and second, when we get there, the thing we want will be a key, not a value. In case there are any other keys besides environmentName they'll be preserved.

这篇关于使用jq或sed替换JSON中的属性或键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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