what linux command can can add new filed key value pair to a json file

柔情痞子 提交于 2021-01-28 03:29:43

问题


I have a json file in a directory and I need to replace the value of a key, add a new value key paire. The json file is in this form:

{

  "Name" : "username",

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

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

}

How can I add or append new key value "Authentication" and "newuser" for my json to look like that?

{

  "Name" : "username",

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

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

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

I know using sed I can replace value of Name as follow in the file.json

sudo sed -i -- 's/"Name" : "Name1"/"Name" : "username"/g' test/file.json

回答1:


Assuming your input JSON is stored in the file input.json, this command adds the Authentication key and an object value for it and the new key (and a value) inside the object associated to the User key:

$ jq '.+{Authentication:{foo:true,poo:false}}|.User.newuser="newpass"' input.json

The jq script, piece by piece:

.            # "." 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

Download jq from https://stedolan.github.io/jq/ and read about how to use it at https://stedolan.github.io/jq/manual/



来源:https://stackoverflow.com/questions/49575500/what-linux-command-can-can-add-new-filed-key-value-pair-to-a-json-file

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