0

How can I write the array to a json file?

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

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

EDIT:

The json file should contain the following:

{
  "testkey": "testvalue",
  "testkey1": "testvalue1", 
  "testkey2": "testvalue2"
}
user5580578
  • 1,134
  • 1
  • 12
  • 28
  • 1
    I wrote an answer and only then stumbled on this, which is a pretty close duplicate: https://stackoverflow.com/questions/44792241/constructing-a-json-hash-from-a-bash-associative-array It has a little bit extra around parsing integers but otherwise it's the same. – Weeble Oct 30 '20 at 13:44
  • 2
    Does this answer your question? [Constructing a json hash from a bash associative array](https://stackoverflow.com/questions/44792241/constructing-a-json-hash-from-a-bash-associative-array) – Weeble Oct 30 '20 at 13:45

2 Answers2

1

Here's a way that doesn't need an extra step before to serialise the associative array:

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

It should work even with newlines in the keys or values. The one caveat is that technically bash doesn't guarantee that ${!myarray[@]} will output the keys 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 that should be safe to newlines. It also assembles a single object.

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

as an alternative to 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[@]}"
vgersh99
  • 877
  • 1
  • 5
  • 9