5

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\"}"
}
Diego Bernardes
  • 179
  • 1
  • 7
  • Does this answer your question? [how to parse a JSON String with jq (or other alternatives)?](https://stackoverflow.com/questions/35154684/how-to-parse-a-json-string-with-jq-or-other-alternatives) – Adam Michalik Dec 07 '22 at 09:09

2 Answers2

10

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.

peak
  • 105,803
  • 17
  • 152
  • 177
1

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).

axiac
  • 68,258
  • 9
  • 99
  • 134