Replace an attribute or key in JSON using jq or sed

我怕爱的太早我们不能终老 提交于 2021-02-04 16:01:07

问题


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"
                    }
                ]
            }
        ]
    }
},

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

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

Tried with sed command as below

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

Tried with jq as below but not working

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

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


回答1:


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

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

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.




回答2:


TL,TR

You can use the following command:

jq '(.envConfig |= (. + {"prod":.environmentName}|del(.environmentName)))' foo.json

Let's say you have the following json:

{
    "foo": {
        "hello" : "world"
    }   
}

You can rename the node foo to bar by first duplicating it and then remove the original node:

jq '. + {"bar":.foo}|del(.foo)' foo.json

Output:

{
    "bar": {
        "hello" : "world"
    }   
}

It get's a bit more complicated if you want to replace a child key somewhere in the tree. Let's say you have the following json:

{
  "test": {
    "foo": {
      "hello": "world"
    }
  }
}

You can use the following jq command for that:

jq '(.test |= (. + {"bar":.foo}|del(.foo)))' foo.json

Note the additional parentheses and the use of the assignment operator |=.

Output:

{
  "test": {
    "bar": {
      "hello": "world"
    }
  }
}



回答3:


Using sed:

sed -i '/^ \"environmentName\":/ s/environmentName/prod/' <yourfile>

Keep in mind that -i will overwrite the file. You may want to make a backup first.



来源:https://stackoverflow.com/questions/42969020/replace-an-attribute-or-key-in-json-using-jq-or-sed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!