Sample Header Ad - 728x90

How to generate double quoted JSON string with escaped double quotes?

3 votes
2 answers
1779 views
I sometimes need to write JSON strings containing a string value that is itself a JSON string. e.g. In the following JSON object: echo '{"rec" : " {\"id\": 1, \"name\": \"x\"}" }' | jq . { "rec": " {\"id\": 1, \"name\": \"x\"}" } the value at "rec" is a json in string form {\"id\": 1, \"name\": \"x\"}". It is tedious to write such escaped json strings, as one needs to escape each double quote " to \". My question is: Given the content { "id": 1, "name": "x"}, is there an automatic way using bash/jq to properly escape the quotes and get the quoted form usable as a JSON string value "{\"id\": 1, \"name\": \"x\"}"?
Asked by tinlyx (1072 rep)
Oct 7, 2024, 08:13 AM
Last activity: Oct 7, 2024, 09:58 AM