使用jq将多个虚拟对象附加到json数组
假设这是我的数组:使用jq将多个虚拟对象附加到json数组,json,random,jq,Json,Random,Jq,假设这是我的数组: [ { "name": "Matias", "age": "33" } ] 我可以这样做: echo "$response" | jq '[ .[] | select(.name | test("M.*"))] | . += [.[]]' echo "$response" | jq '[ .[] | select(.name | test("M.*"))] | . += [.[] * 3]' jq: error (at <stdin>:
[
{
"name": "Matias",
"age": "33"
}
]
我可以这样做:
echo "$response" | jq '[ .[] | select(.name | test("M.*"))] | . += [.[]]'
echo "$response" | jq '[ .[] | select(.name | test("M.*"))] | . += [.[] * 3]'
jq: error (at <stdin>:7): object ({"name":"Ma...) and number (3) cannot be multiplied
它将输出:
[
{
"name": "Matias",
"age": "33"
},
{
"name": "Matias",
"age": "33"
}
]
但我不能这样做:
echo "$response" | jq '[ .[] | select(.name | test("M.*"))] | . += [.[]]'
echo "$response" | jq '[ .[] | select(.name | test("M.*"))] | . += [.[] * 3]'
jq: error (at <stdin>:7): object ({"name":"Ma...) and number (3) cannot be multiplied
echo“$response”| jq'[.]| select(.name | test(“M.*))]|+=[.[] * 3]'
jq:error(at:7):对象({“name”:“Ma…)和数字(3)不能相乘
我需要扩展一个数组来创建一个有100个值的虚拟数组,但我做不到。另外,我希望对象有一个随机的年龄。(因此,稍后我可以过滤文件以测量应用程序的性能。目前jq没有内置的随机化功能,但生成jq可以使用的随机数非常容易。以下解决方案使用了
awk
,但其他一些PRNG可以很容易地使用
#!/bin/bash
function template {
cat<<EOF
[
{
"name": "Matias",
"age": "33"
}
]
EOF
}
function randoms {
awk -v n=$1 'BEGIN { for(i=0;i<n;i++) {print int(100*rand())} }'
}
randoms 100 | jq -n --argfile template <(template) '
first($template[] | select(.name | test("M.*"))) as $t
| [ $t | .age = inputs]
'
!/bin/bash
功能模板{
catHave您在(长度<100;+=[[0]]时尝试了echo“$response”| jq”)“
?jq没有内部的random
函数BTWI如果您不局限于jq,我可以提供一个替代解决方案。@Dimitry,当然。任何工具都可以。我对jq感兴趣,但如果它不起作用,那么一切都可以。@oguzismail有效!(除了您所说的随机部分),谢谢!@MatiasBarrios,如果您正在运行bash
,那么您可以使用jtc
(我开发的json
工具):是的,-eu会减慢速度。