How to parse with jq a json encoded as string inside a json

Viewed 671

There is any way to get parse this json with jq within a single command? I would like to do something like this: jq .key.first. But yea, taking into consideration that the key is a string and need to be first parsed to json.

{
  "key": "{\"first\":\"123\",\"second\":\"456\"}"
}
2 Answers

Use fromjson, e.g.

jq '.key|fromjson|.first'

As pointed out in a comment, this can be abbreviated by omitting the last pipe character.

In general, it’s better to avoid calling jq twice when one call is sufficient.

There is any way to get parse this json with jq within a single command?

It depends on how you define a single command. It can be done using a pipeline that contains two invocations of jq:

INPUT='{
  "key": "{\"first\":\"123\",\"second\":\"456\"}"
}'

echo "$INPUT" | jq -r .key | jq .

jq -r .key tells jq to echo the raw value of .key, not its JSON representation (it is a string, normally jq outputs it as it is represented in the input JSON).

The output is:

{
  "first": "123",
  "second": "456"
}

The second invocation of jq (jq .) doesn't do anything to the data; it just format it nicely (as depicted above) and coloured (it does not colour the output if it does not go to the terminal).

However, it shows that its input is a JSON (the raw value of .key) that can be processed further. You can, for example, use jq .first instead to get "123" (the string encoded as JSON) or jq -r .first to get 123 (the raw value).

Related