[英]How to dynamically update one json object and put it back into the original json objects?
如何动态更新一个 JSON object 并放回原来的 JSON 对象变量?
我有一个变量,其中包含以下 JSON 数据。
test='[
{
"Name": "James",
"Mobile": 12345678,
"Gender": "Male",
"Boolean": true,
"Pet": "cat"
},
{
"Name": "John",
"Mobile": 1234567875,
"Gender": "Male",
"Boolean": true,
"Pet": "rat"
},
{
"Name": "Jennifer",
"Mobile": 1234567890,
"Gender": "Female",
"Boolean": true,
"Pet": "Dog"
},
{
"Name": "Julia",
"Mobile": 1234567890,
"Gender": "Female",
"Boolean": true,
"Pet": "Dog"
},
{
"Name": "Jeff",
"Mobile": 9871234567890,
"Gender": "Male",
"Boolean": true,
"Pet": "Fish"
},
{
"Name": "Jones",
"Mobile": 79871234567890,
"Gender": "Female",
"Boolean": true,
"Pet": "Parrot"
}
]'
items=$(echo "$test" | jq -c -r '.[]')
for item in ${items[@]}; do
uName=$(echo $item | jq -r '.Name')
if [ "$uName" == "John" ]; then
echo "$item"
echo " "
modifiedTest=$(echo "$item" | jq '.Name = "Tom"')
modifiedTest=$(echo "$modifiedTest" | jq '.Pet = "rabbit"')
echo "$modifiedTest"
fi
done
现在假设我们从上面的 JSON 个对象中得到下面的第二个 JSON object
{
"Name": "John",
"Mobile": 1234567875,
"Gender": "Male",
"Boolean": true,
"Pet": "rat"
}
我们已将上面选择的 JSON object 字段更新为以下内容
{
"Name": "Tom",
"Mobile": 1234567875,
"Gender": "Male",
"Boolean": true,
"Pet": "rabbit"
}
现在我们如何将上面修改过的 JSON object 添加/更新到原始对象列表变量“test”中,确切位置为 position(在本例中为第 2 个 position),但使用“Name=John”过滤器并以动态方式我们不这样做使用 bash 脚本不知道这个 object 的确切索引 position?
工具jq
可用于 JSON 操作:
jq '.[1].Name = "Tom" | .[1].Pet = "rabbit"' data.json
这将 output 修改后的文件显示在控制台上。
请注意,一般情况jq [filter] data.json > data.json
将不起作用,即使看起来如此,也应避免以这种方式覆盖输入文件。 一种选择是使用 shell 变量:
json_data=$(jq '.[1].Name = "Tom" | .[1].Pet = "rabbit"' data.json)
echo $json_data > data.json
另一种选择是使用临时文件; 还有一种方法是在moreutils中使用诸如sponge
之类的实用程序。
请注意,您显示的文件无效 JSON,因此 jq 将无法将其读取为 JSON。为了修复它,我用[
和]
包围了所有内容,并删除了John
object 中多余的逗号。
如果我们不知道这个 object 的确切索引 position 并使用 'Name=John' 过滤器怎么办
< data.json jq '
(map(.Name)| index("John")) as $ix
| (select($ix)
| .[$ix] |= (.Name = "Tom" | .Pet = "rabbit")) // .
' | sponge data.json
但是您可能需要先备份 data.json。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.