70

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

3 Answers 3

124

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.
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your response. Can you please how can i get output in format rhel12/rhel6.6 In other words, I need o/p in format namespace/name
@meallhour, jq -r '.[] | .[] | [.namespace, .name] | join("/")' test.json
39

You want to look at the repositories array instead of treating the input as an array:

$ jq -r '.repositories[].name' file
rhel6.6
rhel7

Comments

18

Here is another solution. Assuming the requirements

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

Can you please how can i get output in format rhel12/rhel6.6 In other words, I need o/p in format namespace/name

if the data is in data.json then the command

jq -M -r '.repositories[] | "\(.namespace)/\(.name)"' data.json

should produce

rhel12/rhel6.6
rhel12/rhel7

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.