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\"}" } 
1

2 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

I was trying to do within a single jq command instead of using a pipe. But yea, this works too. Thanks!
this solves too: jq -r '[.key|fromjson][0].first'
Indeed. I didn't know about fromjson. It does not need to be wrapped into an array. jq -r '.key|fromjson.first is enough.
Indeed, I was following an example, my bad.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.