LOrD_ARaGOrN
LOrD_ARaGOrN

Reputation: 4486

Shell Script: How to add json objects to a json output without using jq or any other tool

I am getting below output after executing a script, which I store in a variable

{
  "VariaB": "DONE",
  "VariaC": "DONE",
  "VariaD": null,
  "VariaE": true
}

I have another variable VariaA="ABCD" & VariaF which contains value true or false and want to insert in variable value. I want to print the final variable in below format

{
  "VariaA": "ABCD",
  "VariaB": "DONE",
  "VariaC": "DONE",
  "VariaD": null,
  "VariaE": true,
  "VariaF": false
}

Upvotes: 1

Views: 1677

Answers (3)

Francesco Gasparetto
Francesco Gasparetto

Reputation: 1963

This pipeline does what you need

echo "{"`echo $VariaA | sed "s/{\|}//g"`,`echo "   "$VariaF | sed "s/{\|}//g"`"}" | sed "s/,/,\n/g" | sed "s/{/{\n/" | sed "s/}/\n}/" | uniq 

Upvotes: 1

Aaron
Aaron

Reputation: 24802

As others said, please do your best to use a JSON-aware tool rather than basic string manipulation, it would be bound to save yourself some effort in the future if not some trouble.

Since you said you currently can't, here's a string manipulation "solution" :

printf "{
  \"VariaA\": \"$VariaA\",
%s
  \"VariaF\": $VariaF
}" "$(grep -v '[{}]' <<< "$input")"

printf handles the whole structure, and takes as parameter the middle block that is from your input. To get that middle block, we use grep to exclude the lines that contain brackets.

Note that this will fail in a lot of cases such as the input not being formatted as usual (a one liner would be proper JSON, but would make that script fail) or suddenly containing nested objects, the variables containing double-quotes, etc.

You can try it here.

Upvotes: 1

nbari
nbari

Reputation: 26925

Looks yout output is JSON, for appending to your output object you could use jq for example try this:

cat json.txt | jq --arg VariaA  ABCD '. + {VariaA: $VariaA}'

In this case, if json.txt contains your input:

{
  "VariaB": "DONE",
  "VariaC": "DONE",
  "VariaD": null,
  "VariaE": true
}

By using jq --arg VariaA ABCD '. + {VariaA: $VariaA}' it will then output:

{
  "VariaB": "DONE",
  "VariaC": "DONE",
  "VariaD": null,
  "VariaE": true,
  "VariaA": "ABCD"
}

If you would like to use more variables you need to use --arg multiple times, for example:

 jq --arg VariaA ABCD --argjson VariaX true '. + {VariaA: $VariaA, VariaX: $VariaX}'

The output will be:

{
  "VariaB": "DONE",
  "VariaC": "DONE",
  "VariaD": null,
  "VariaE": true,
  "VariaA": "ABCD",
  "VariaX": "true"
}

In this example cat json.txt simulates your command output but worth mention that if you wanted to process an existing file you could use (notice the <):

jq --arg VariaA  ABCD '. + {VariaA: $VariaA}' < file.txt

By doing this you do all in one single process.

Upvotes: 0

Related Questions