Home > Software design >  How to create a json file with jq
How to create a json file with jq

Time:09-29

Now I am trying to make a json file. I found an example which is with jq.

echo "$(jq -n '{Test1: $ARGS.named}' \
  --arg one 'Apple' \
  --arg two 'Banana')" >> config.json

I can get the result and save it into config.json

{
  "Test1": {
    "one": "Apple",
    "two": "Banana"
  }
}

Now, how to make the following result and save it.

{
  "Test1": {
    "one": "Apple",
    "two": "Banana"
  },
  "Test2": {
    "one": "Kiwi",
    "two": "Tomato"
  }  
}

Thanks

CodePudding user response:

Create a JSON file:

$ jq -n --arg one 'Apple' --arg two 'Banana' \
  '{Test1: $ARGS.named}' > config.json

View the JSON file:

$ cat config.json
{
  "Test1": {
    "one": "Apple",
    "two": "Banana"
  }
}

Create another JSON file based on the first one (using jq's . for the input object, and to add (merge) two objects):

$ jq --arg one 'Kiwi' --arg two 'Tomato' \
  '.   {Test2: $ARGS.named}' config.json > config2.json

View that other JSON file:

$ cat config2.json
{
  "Test1": {
    "one": "Apple",
    "two": "Banana"
  },
  "Test2": {
    "one": "Kiwi",
    "two": "Tomato"
  }
}

Overwrite the first one with the second one:

$ mv config2.json config.json

Now the first one has the content of the second one:

$ cat config.json
{
  "Test1": {
    "one": "Apple",
    "two": "Banana"
  },
  "Test2": {
    "one": "Kiwi",
    "two": "Tomato"
  }
}

CodePudding user response:

Without creating a temporary file, assuming your shell is POSIX-based:

{
  jq -cn  --arg one 'Apple' --arg two 'Banana' '{Test1: $ARGS.named}'
  jq -cn  --arg one 'Kiwi'  --arg two 'Tomato' '{Test2: $ARGS.named}'
} | jq -s add > output.json

Or

jq -n \
   --argjson Test1 "$(jq -n --arg one 'Apple' --arg two 'Banana' '$ARGS.named')" \
   --argjson Test2 "$(jq -n --arg one 'Kiwi'  --arg two 'Tomato' '$ARGS.named')" \
  '$ARGS.named' > output.json

If this is a prelude to a list of "TestN" objects, we'll get a bit more programmitic, here with bash syntax:

ones=( Apple Kiwi )
twos=( Banana Tomato )

for ((i=0; i < ${#ones[@]}; i  )); do
  jq -cn \
     --arg one "${ones[i]}" \
     --arg two "${twos[i]}" \
     --arg key "Test$((i   1))" \
     '{($key): {$one, $two}}'
done | jq -s add > output.json

Or, use a different tool: jo

jo Test1="$(jo one=Apple two=Banana)" Test2="$(jo one=Kiwi two=Tomato)"
{"Test1":{"one":"Apple","two":"Banana"},"Test2":{"one":"Kiwi","two":"Tomato"}}
  • Related