json - 如何使用 bash 脚本将 json 值添加到 json 文件
问题描述
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"
解决方案
您可以使用名为jq的轻量级 JSON处理器
加载文件后,您可以使用 jq '.InstanceType = "This is instance value"