【发布时间】:2021-05-18 06:32:18
【问题描述】:
我有这个 json 文件:
{
"name": "market",
"type": "grocery",
"shelves": {
"upper_one": [
"23423565",
"23552352",
"08789089"
]
}
}
我需要遍历列表的每个元素(upper_one),并将其替换为其他值。
我试过这段代码:
#/bin/bash
for product in $(cat first-shop.json| jq -r '.shelves.upper_one[]')
do
cat first-shop.json| jq --arg id "$((1 + $RANDOM % 10))" --arg product "$product" -r '.shelves.upper_one[]|select(. == $product)|= $id'
done
但是我得到了这样的输出:
1
23552352
08789089
23423565
10
08789089
23423565
23552352
7
是否可以用 jq 迭代列表,用另一个函数的值替换值(如代码中的 $id),并用替换值打印整个最终 json?
我需要这种输出:
{
"name": "market",
"type": "grocery",
"shelves": {
"upper_one": [
"1",
"10",
"7"
]
}
}
不仅仅是“upper_one”列表三次的元素。
【问题讨论】:
-
你想用什么替换它们?随机数?
-
不,我在脚本中有另一个函数,可以生成我需要的文本。这只是一个例子。
-
你能展示你的脚本的示例输出吗?例如,它是否已经有 json 引号?
-
@Aserre 示例输出位于“但我得到了这种输出:”部分
-
我的意思是当你说
I have another function in the script, that would generate the text I need。只是生成文本,还是正确的 json(带引号)?