【问题标题】:how to add json value to json file using bash script如何使用 bash 脚本将 json 值添加到 json 文件
【发布时间】:2019-10-24 16:00:25
【问题描述】:

Json文件如下:

{

      "ImageId": "ami-074acc26872f26463",
      "KeyName": "Accesskeypair",
      "SecurityGroupIds": ["sg-064caf9c470e4e8e6"],
      "InstanceType": ""
      "Placement": {
        "AvailabilityZone": "us-east-1a"
      }
}

从用户读取类型#input

现在我想使用 bash 脚本在“InstanceType”中添加 json 值:“$type”我尝试过 sed、cat 和 echo

echo "Hello"
echo "lets create an instance"  
echo "please enter the type of instance you need"
read instance_type;
echo $type
 sed -a '|\InstanceType": "|$instance_type|a' awsspotinstancecreation.json
 sed -e '/\"InstanceType": "|$instance_type|/a' awsspotinstancecreation.json
 sed -i "/\InstanceType": "/ s/^\(.*\)\('\)/\1, $instance_type/" awsspotinstancecreation.json
 sed -e 's/^"InstanceType": "",.*$/"InstanceType": "$instance_type",/g' awsspotinstancecreation.json
 sed -i 's/^InstanceType .*$/"InstanceType": "$instance_type",/' awsspotinstancecreation.json
 sed -i 's:^"InstanceType": "",.*$:"InstanceType": "$instance_type",:a' awsspotinstancecreation.json

但是当我这样做时,会出现 "InstanceType": "$type" 而不是 "InstanceType": "t2.small"

【问题讨论】:

  • 请返回并编辑您的original question
  • 您的文件是无效的 json。您的 InstanceType 值后缺少逗号。就像我在另一个线程中所说,不要使用sed,使用jq

标签: json bash shell


【解决方案1】:

您可以使用名为 jq

的轻量级 JSON 处理器

加载文件后,您可以使用 jq '.InstanceType = "This is instance value"

可以参考Add a new element to an existing JSON array using jq

【讨论】:

    【解决方案2】:

    使用-e 选项不会修改文件,而是会在终端打印输出。

    -i 选项将修改文件。

    使用.* 正则表达式将更新文件和具有任何值的特定键

    使用\"\" 只会查找空字符串并更新值。

    试试这个:

    sed -i "s/\"InstanceType\":.*,$/\"InstanceType\": \"${instance_type}\",/g" awsspotinstancecreation.json

    sed -i "s/\"InstanceType\": \"\",$/\"InstanceType\": \"${instance_type}\",/g" awsspotinstancecreation.json

    【讨论】:

    • 非常感谢兄弟!!!它工作得很好,感谢您的解释......意义重大!
    猜你喜欢
    • 2013-05-25
    • 1970-01-01
    • 2020-07-23
    • 2021-06-04
    • 2021-02-08
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多