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"
}
2

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Nice! but do add a note $ARGS.positional is a jq-1.6 thingy
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[@]}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.