linux命令可以将新的键值对添加到json文件中 [英] what linux command can can add new filed key value pair to a json file

查看:331
本文介绍了linux命令可以将新的键值对添加到json文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

}

如何为我的json添加或附加新的密钥值"Authentication"和"newuser"?

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

我知道使用sed可以替换file.json中的Name值

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

推荐答案

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

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

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

https://stedolan.github.io/jq/,并在 https://stedolan.github.io/jq/manual中了解如何使用它/

这篇关于linux命令可以将新的键值对添加到json文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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