I have a valid JSON values that is generated from using JQ from a string,
# key1:value1,key2:value2 --> {"key1":"value1","key2":"value2"}
input='key1:value1,key2:value2'
json=$( jq -Rc 'split(",") | map( split(":") | {(.[0]): .[1]}) add |' <<<"$input" )
echo $json
This works perfectly fine but now I want to convert the json to string without escaping the double quotes of each key and value and just need to add single quotes at the end.
# {"key1":"value1","key2":"value2"} ---> '{"key1":"value1","key2":"value2"}'
I tried the tostring function but it escapes all double quotes
strJson=$(jq tostring <<< "$json")
echo $strJson
Add @json to encode the result as JSON, then add @sh to escape the string for Shell compatibility, and replace the -c option to -r for raw output:
jq -Rr 'split(",") | map( split(":") | {(.[0]): .[1]}) | add | @json | @sh' <<<"$input"
'{"key1":"value1","key2":"value2"}'
Demo
Addendum: This solution follows the expressed requirement to wrap a JSON document in single quotes without escaping the double quotes inside. However, as it is/was unclear for what or how the resulting data is being used, and to shed more light on the ongoing discussion thereof, storing the plain JSON result in a shell variable and using it as an argument to another program may as well be what the OP was trying to achieve:
#!/bin/bash
input='key1:value1,key2:value2'
json="$(jq -Rc 'split(",") | map( split(":") | {(.[0]): .[1]}) | add' <<<"$input")"
program --set-argument "$json"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With