How to Add JSON Object to JSON File Using Shell Script

how to add json object to json file using shell script


sed -i '$s/}/,\n"location":"canada"}/' sample.json

Result:

{"name" :"sam",
"age":23,
"designation":"doctor",
"location":"canada"}

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

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.

Insert a JSON object at the end of a JSON file using shell script in linux

You can use jq to add a new key-value pair to the object in config.json, then write the new object back to disk.

jq '.proxies = {
"default": {
"httpProxy": "http://proxy.xyz.com:123",
"httpsProxy": "http://proxy.xyz.com:123",
"noProxy": "127.0.0.1,localhost"
}
}' ~/.docker/config.json > tmp && mv tmp ~/.docker/config.json

Everything in jq is a filter: they take a stream of JSON values as inputs, and return a stream of JSON values as output. Assignment is no different.

In the filter x = y, x is a path expression and y is an ordinary filter. x is evaluated using the input to determine the "target" for the assignment. y is applied to the input, and its output is assigned to the target specific by x.

In this case, the input is the entire contents of config.json. .proxies specifies a key in an object, and the {...} expression is a filter that ignores the input and produces a JSON object. That JSON object is that added to the input under the proxies key, and the modified object is returned as the output, which jq then writes to standard output.

The result is written to a new file so that we don't overwrite config.json before we can read it. Assuming jq succeeds, we can then replace the old config.json with the new file tmp.

jq itself cannot write to a file, only standard output. It can read JSON values either from standard input or from files named as arguments.

How to add a new JSON object in an existing JSON file using jq and variable arguments

Define them using --arg, then set them using +=. That way you can always add more subitems.

jq --arg parent_key aiops \
--arg child_key catalog_source \
--arg child_val abc.com/123 \
'.[$parent_key] += {($child_key): $child_val}' input.json
{
"cluster": "bvt-rtp-123",
"state": "installed",
"timestamp": "2022-02-14T10:23:01Z",
"aiops": {
"catalog_source": "abc.com/123"
}
}

Demo for the jq filter (simulating argument input with variable declaration)

how to add json value to json file using bash script

use -e option will not modify the file instead it will print the output in terminal.

-i option will modify the file.

using .* regex will update the file and particular key having any value

and using \"\" will only look for empty string and update the value.

try this:

sed -i "s/\"InstanceType\":.*,$/\"InstanceType\": \"${instance_type}\",/g" awsspotinstancecreation.json

OR

sed -i "s/\"InstanceType\": \"\",$/\"InstanceType\": \"${instance_type}\",/g" awsspotinstancecreation.json

jq: Append JSON object via shell variable


  1. Use --argjson rather than --arg when passing JSON rather than strings.

  2. When in doubt, quote your strings; that way if the shell executing your code isn't the one you think it is, you won't have your values being munged. (It's also helpful to stay in the habits necessary to write portable code; the whole reason I dropped zsh after spending 6 months learning it back in the mid-2000s is that my code quality when writing for other shells suffered).



objName="objName"
objJSON='{"test": "json"}'
echo '{"data":{}}' |
jq --arg objectName "$objName" \
--argjson jsonString "$objJSON" \
'.data[$objectName] += $jsonString'

...properly emits:

{
"data": {
"objName": {
"test": "json"
}
}
}

Adding dynamically an object to a json file using jq in a bash script

Finally, the chosen code, at least a valid one for my case, is:

touch credScanSuppressionsFile.json
echo '{"tool": "Credential Scanner", "suppressions":[]}' | jq > credScanSuppressionsFile.json

webapp_name=customer-brasil-forms

for env in develop #staging demo preprod prod
do
file=$env-$webapp_name.json
echo $file
jq --arg file $file '.suppressions += [{"file": $file, "_justification": "app setting file"}]' <<< "$(cat credScanSuppressionsFile.json)" > credScanSuppressionsFile.json
done

I have realised that just using the name of the file is enough.

Things to highlight is that @Armali is right, the json as it was (my supposed wrong result) is correct and the backslash should be scaped with double backslash and @LeaGris thanks for your help, but the code was correct after the edition, the errors you see its just info in case you want to use it.

touch credScanSuppressionsFile.json
echo '{"tool": "Credential Scanner", "suppressions":[]}' | jq > credScanSuppressionsFile.json

webapp_name=customer-brasil-forms

for env in develop staging demo preprod prod
do
file='azure_portal_variables\'$env-$webapp_name.json
echo $file
jq --arg file $file '.suppressions += [{"file": $file, "_justification": "app setting file"}]' <<< "$(cat credScanSuppressionsFile.json)" > credScanSuppressionsFile.json
done

This code is also correct



Related Topics



Leave a reply



Submit