Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON to String surrounded by Single Quotes Bash / JQ

Tags:

json

string

bash

jq

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
like image 429
Faisal Avatar asked Dec 14 '25 22:12

Faisal


1 Answers

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"
like image 180
pmf Avatar answered Dec 16 '25 16:12

pmf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!