Sample input JSON is given below: I want the code to construct the JSON object static/dynamically in KSH/BASH
Example :
```{
"param1": "value1",
"param2": "value2",
"param3": "value3"
}```
Nested JSON:
```{
"param1": "value1",
"param2": "value2",
"param3": {
"param4": "value4",
"param5": "value5"
}
}```
CodePudding user response:
Using jq to generate your JSON will save you when the input data contains things like quotation marks.
simple JSON object
json=$( jq -n \ --arg "$param1" "$value1" \ --arg "$param2" "$value2" \ --arg "$param3" "$value3" \ '$ARGS.named' )
nested
nestedJson=$( jq -n \ --arg "$param1" "$value1" \ --arg "$param2" "$value2" \ --arg "$param3" "$value3" \ --argjson "nested" "$json" \ '$ARGS.named' )
dynamic: use bash associative arrays
declare -A data=([param4]="value4" [param5]="value5") jq_args=( -n --arg "$param1" "$value1" --arg "$param2" "$value2" ) for key in "${!data[@]}"; do jq_args =( --arg "$key" "${data[$key]}" ) done dynamicJson=$( jq "${jq_args[@]}" '$ARGS.named'
CodePudding user response:
Preparing the JSON in KSH/Bash
json=$(cat <<-END { "${param1}": "${value1}", "${param2}": "${value2}", "${param3}": "${value3}" } END )
Preparing the Nested-JSON in KSH/Bash
nestedJson=$(cat <<-END { "${param1}": "${value1}", "${param2}": "${value2}", "${param3}": "${value3}", "nested" : ${json} } END )
Dynamic JSON:
array=("param4:value4", "param5:value5") dynamicJSON=$(cat <<-END { "${param1}": "${value1}", "${param2}": "${value2}" } END ) for element in ${array[@]} do key="$(cut -d":" -f1 <<<"$element")" val="$(cut -d":" -f2 <<<"$element")" dynamicJSON=$( sed '$s/}/,\n'"\"$key\""':'"\"$val\""'}/' <<<"$dynamicJSON") done
CodePudding user response:
You can reference environment variables directory in your jq program using env.varname
$ export fname="foo"
$ export lname="bar"
$ export location="baz"
$ SAMPLE_JSON='{
"first_name": "",
"last_lname": "",
"location": "",
"key": "value"
}'
$ jq '{
"first_name":env.fname,
"last_lname":env.lname,
"location":env.location,
"key": .key
}' <<<"$SAMPLE_JSON"
{
"first_name": "foo",
"last_lname": "bar",
"location": "baz",
"key": "value"
}
Nested
SAMPLE_JSON='{
"param1": "value1",
"param2": "value2",
"param3": {
"param4": "value4",
"param5": "value5"
}
}'
jq '{
"param1": env.fname,
"param2": env.lname,
"param3": {
"param4": .param3.param4,
"param5": env.location
}
}' <<<"$SAMPLE_JSON"
{
"param1": "foo",
"param2": "bar",
"param3": {
"param4": "value4",
"param5": "baz"
}
}