Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jq to fetch key value from json output

I have a file that looks as below:

{   "repositories": [    {     "id": "156c48fc-f208-43e8-a631-4d12deb89fa4",     "namespace": "rhel12",     "namespaceType": "organization",     "name": "rhel6.6",     "shortDescription": "",     "visibility": "public"    },    {     "id": "f359b5d2-cb3a-4bb3-8aff-d879d51f1a04",     "namespace": "rhel12",     "namespaceType": "organization",     "name": "rhel7",     "shortDescription": "",     "visibility": "public"    }   ]  } 

I want to get only name values with each of them in a new line so that I can use while read -r line. I need only

rhel6.6  rhel7 

I am using jq as follows which doesn't seem to work:

jq -r '.[].name' 

Please suggest correct use of jq here

like image 414
meallhour Avatar asked Sep 30 '16 19:09

meallhour


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.

Can a value be the key in JSON?

Keys must be strings, and values must be a valid JSON data type: string. number.


1 Answers

You need to combine filters by means of | operator:

$ jq -r '.[] | .[] | .name' test.json  rhel6.6 rhel7 

The first .[] fetches repositories array. The next .[] fetches all the items of the repositories array. Finally, .name extracts properties from the array items(objects).

Note, the first .[] works on object because it is a documented feature:

.[]     If you use the .[index] syntax, but omit the index entirely, it     will return all of the elements of an array...      You can also use this on an object, and it will return all the     values of the object. 
like image 85
Ruslan Osmanov Avatar answered Sep 28 '22 02:09

Ruslan Osmanov