Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a specific field from JSON output using jq

Tags:

json

jq

I have a JSON output as follows:

{   "example": {     "sub-example": [       {         "name": "123-345",         "tag" : 100       },       {         "name": "234-456",         "tag" : 100       },       {         "name": "4a7-a07a5",         "tag" : 100       }     ]   } } 

I want to extract the values of the three "name" fields and store it in three variables.

I tried cat json_file | jq '.["example.sub-example.name"]' to extract the value of the "name" field but that doesn't work.

Can anyone tell me how to achieve this using jq (or some other method)?

like image 523
rmb Avatar asked Aug 30 '16 13:08

rmb


People also ask

Can jq validate JSON?

jq – a lightweight and flexible CLI processor – can be used as a standalone tool to parse and validate JSON data.

What is jq curl?

jq is a program described as “ sed for JSON data": You can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.

What is the output of jq?

jq usually outputs non-ASCII Unicode codepoints as UTF-8, even if the input specified them as escape sequences (like "\u03bc"). Using this option, you can force jq to produce pure ASCII output with every non-ASCII character replaced with the equivalent escape sequence.

What is jq parser?

jq is a lightweight and flexible command-line JSON processor and, we could say it is like awk or sed, but for JSON syntax. It may installed via apt in Ubuntu, or downloaded directly from github.


2 Answers

If you just want to extract the name fields, the command you're looking for is jq '.example."sub-example" | .[] | .name'. If you want to keep the names in an array, wrap the whole jq expression in square brackets.

like image 158
aaaaaa123456789 Avatar answered Sep 16 '22 13:09

aaaaaa123456789


In jq 1.3, you can use the filter to extract the values:

.example["sub-example"] | .[] | .name 

Or more compactly:

.example["sub-example"][].name 

These of course also work with later versions of jq as well.

Reading into shell variables

Rather than populating separate shell variables (which would require knowing in advance how many values there are), consider populating a shell array. For example, using a bash shell with mapfile (aka readarray):

mapfile -t ary < <(< json_file jq '.example."sub-example"[].name') 

You could alternatively use a shell while loop. Etc etc. There are many SO Qs on this topic.

like image 34
peak Avatar answered Sep 20 '22 13:09

peak