How to prettify json with jq given a string with escaped double quotes

I would like to pretty print a json string I copied from an API call which contains escaped double quotes.

Similar to this:

"{\"name\":\"Hans\", \"Hobbies\":[\"Car\",\"Swimming\"]}"

However when I execute pbpaste | jq "." the result is not changed and is still in one line.

I guess the problem are the escaped double quotes, but I don’t know how to tell jq to remove them if possible, or any other workaround.

>Solution :

What you have is a JSON string which happens to contain a JSON object. You can decode the contents of the string with the fromjson function.

$ pbpaste | jq "."
"{\"name\":\"Hans\", \"Hobbies\":[\"Car\",\"Swimming\"]}"
$ pbpaste | jq "fromjson"
{
  "name": "Hans",
  "Hobbies": [
    "Car",
    "Swimming"
  ]
}

Leave a Reply