什么 linux 命令可以将新的归档键值对添加到 json 文件中

lud*_*udo 2 linux bash command-line json

我在一个目录中有一个 json 文件,我需要替换一个键的值,添加一个新的值键对。json 文件格式如下:

{

  "Name" : "username",

  "Actionchecked" : {
    "Enablecheck" : true,
    "savecheck" : true,
  },

  "User" : {
    //"user" : "pass"
  }

}
Run Code Online (Sandbox Code Playgroud)

如何为我的 json 添加或附加新的密钥值“身份验证”和“新用户”以使其看起来像这样?

{

  "Name" : "username",

  "Actionchecked" : {
    "Enablecheck" : true,
    "savecheck" : true
  },

  "Authentication" : {
    "foo" : true,
    "poo" : false

  "User" : {
    //"user" : "pass"
    "newuser" : newpass"
  }
}
Run Code Online (Sandbox Code Playgroud)

我知道使用 sed 我可以替换 file.json 中的 Name 值,如下所示

sudo sed -i -- 's/"Name" : "Name1"/"Name" : "username"/g' test/file.json
Run Code Online (Sandbox Code Playgroud)

axi*_*iac 5

假设您的输入 JSON 存储在文件中input.json,此命令会添加Authentication键和对象值,以及与键关联的对象内的新键(和值)User

$ jq '.+{Authentication:{foo:true,poo:false}}|.User.newuser="newpass"' input.json
Run Code Online (Sandbox Code Playgroud)

jq一段一段的脚本:

.            # "." is the current item (there is only one object in your input)
+            # "+" is addition; for objects it merges the keys and properties
{Authentication:{foo:true,poo:false}}
             # the object to add to the current item 
|            # pipe the output of the previous filter to the next filter
.User.newuser
             # the "newuser" property of the "User" property of the current item
=            # assign a value to .User.newuser
"newpass"    # the new value to assign to .User.newuser
Run Code Online (Sandbox Code Playgroud)

下载jqhttps://stedolan.github.io/jq/和阅读有关如何在使用它https://stedolan.github.io/jq/manual/