1

Is there any way to create nested json in bash.

{
  "t1": {
        "k1": "v1",
        "k2": "v2"
  },
  "t2": {
        "k1": "v1",
        "k2": "v2"
  }
}

I have 2 variable having space separated values.

var1="aa bb cc dd" -- which gives t1,t2 etc in the sample json
var2="ee ff gg hh" -- which gives k1,k2 etc in the sample json

Upon iterating the variables i should derive the values of t's, k's and v's in the json. Below is the loop which i'm thinking to have. However can be changed based on the suggestion.

for i in var1;
do
   -----
   -----
   for j in var2;
   do
     -----
     'json creation'
   done
 done
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Ashwin
  • 439
  • 1
  • 7
  • 23

2 Answers2

1

Here's an only-jq solution. Notice that all the iteration can be done within the jq program itself:

jq -n --arg var1 "$var1" --arg var2 "$var2" '
  [$var2|splits("  *")] as $v2
  | (reduce range(0; $v2|length) as $i ({};
       . + { ($v2[$i]): "v\($i + 1)" })) as $o
  | reduce ($var1|splits("  *")) as $v1 ({};
      setpath([$v1]; $o) )
'

Example

With:

var1="t1 t2"
var2="k1 k2"

the output would be as shown in the Q, i.e.:

{
  "t1": {
    "k1": "v1",
    "k2": "v2"
  },
  "t2": {
    "k1": "v1",
    "k2": "v2"
  }
}
peak
  • 105,803
  • 17
  • 152
  • 177
-1

This can get you started. It uses jq, but I'm not yet familiar enough with it, so there could be easier way to achieve your goal.

#!/bin/bash

v1='k1 v1 k2 v2 double "'

jq -n "$(while : ; do
    k=${v1%% *}
    v1=${v1#* }
    v=${v1%% *}
    v1=${v1#* }
    jq --arg k "$k" --arg v "$v" -n '{($k): $v}'
    [[ $v1 == *' '* ]] || break
    printf +
done)"

As shown, it works even if the variable contains double quotes.

Using a higher-level language with JSON support seems much easier:

perl -MJSON -le 'print encode_json({@ARGV})' $v1

For more variables, it gets a bit more hairy:

perl -MJSON -le 'print encode_json(
    {map +("t" . ++$i, {split}), @ARGV}
)' -- "$v1" "$v2"

i.e. it splits each variable on whitespace and prepends a key to a hash created from it.

choroba
  • 231,213
  • 25
  • 204
  • 289
  • thanks for the quick suggestion. This creates a simple json, i'am stuck at creating the nested part, i was able to get the similar one through https://stackoverflow.com/a/48470227/1532599 . – Ashwin Dec 11 '19 at 13:51