sh:如何使用 jq 将数组写入 json 文件

sh: How to write an array to a json file using jq

如何将数组写入 json 文件?

#!/bin/sh
declare -A myarray 
myarray["testkey"]="testvalue"
myarray["testkey1"]="testvalue1"
myarray["testkey2"]="testvalue2"

jq -n --arg $myarray[@] > file.json

编辑:

json 文件应包含以下内容:

{
  "testkey": "testvalue",
  "testkey1": "testvalue1", 
  "testkey2": "testvalue2"
}

作为jq的替代:

#!/bin/sh
declare -A myarray
myarray["testkey"]="testvalue"
myarray["testkey1"]="testvalue1"
myarray["testkey2"]="testvalue2"

cols=$(printf "%s," "${!myarray[@]}")
column -J --table-name 'myTable' --table-columns "${cols}"  <<<"${myarray[@]}"

这是一种不需要额外步骤就可以序列化关联数组的方法:

jq -n '
    $ARGS.positional|
    . as $a|
    (length/2) as $l|
    [range($l)|{key:$a[.],value:$a[.+$l]}]|
    from_entries' --args "${!myarray[@]}" "${myarray[@]}"

它甚至可以在键或值中使用换行符。需要注意的是,技术上 bash 不能保证 ${!myarray[@]} 将输出对换行应该安全的键 in the same order that ${myarray[@]} will output the values. It does do that in practice, and it's hard to imagine an implementation that wouldn't, but if you really want to be safe here's a variation on Inian's answer。它还组装了单个对象。

for key in "${!myarray[@]}"; do 
    printf "%s[=11=]%s[=11=]" "$key" "${myarray[$key]}"
done | 
jq -sR '
    split("\u0000")|
    . as $elements|
    [range(length/2)|{key:$elements[2*.],value:$elements[2*.+1]}]|
    from_entries'