简体   繁体   English

使用 jq 从 Bash 数组创建对象数组

[英]Creating Array of Objects from Bash Array using jq

I am trying to create an array of objects in bash given an array in bash using jq.我正在尝试使用 jq 在 bash 中给定一个数组,在 bash 中创建一个对象数组。

Here is where I am stuck:这是我被困的地方:

IDS=("baf3eca8-c4bd-4590-bf1f-9b1515d521ba" "ef2fa922-2038-445c-9d32-8c1f23511fe4")
echo "${IDS[@]}" | jq -R '[{id: ., names: ["bob", "sally"]}]'

Results in:结果是:

[
   {
     "id": "baf3eca8-c4bd-4590-bf1f-9b1515d521ba ef2fa922-2038-445c-9d32-8c1f23511fe4",
     "names": [
       "bob",
       "sally"
     ]
   }
]

My desired result:我想要的结果:

[
   {
     "id": "baf3eca8-c4bd-4590-bf1f-9b1515d521ba",
     "names": [
       "bob",
       "sally"
     ]
   },
   {
     "id": "ef2fa922-2038-445c-9d32-8c1f23511fe4",
     "names": [
       "bob",
       "sally"
     ]
   }
]

Any help would be much appreciated.任何帮助将非常感激。

Split your bash array into NUL -delimited items using printf '%s\\0' , then read the raw stream using -R or --raw-input and within your jq filter split them into an array using split and the delimiter "\" :使用printf '%s\\0'将 bash 数组拆分为NUL分隔项,然后使用-R--raw-input读取原始流,并在jq过滤器中使用split和分隔符"\"

printf '%s\0' "${IDS[@]}" | jq -R '
  split("\u0000") | map({id:., names: ["bob", "sally"]})
'
for id in "${IDS[@]}" ; do
  echo "$id"
done | jq -nR '[ {id: inputs, names: ["bob", "sally"]} ]'

or as a one-liner:或作为单线:

printf "%s\n" "${IDS[@]}" | jq -nR '[{id: inputs, names: ["bob", "sally"]}]'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM