Home > Enterprise >  Get values from under different keys in JSON with jq
Get values from under different keys in JSON with jq

Time:11-29

When I have an following JSON,

{
  "group1": [
    {
      "name": "name_AAA",
      "size": 1
    },
    {
      "name": "name_BBB",
      "size": 2
    }
  ],
  "group2": [
    {
      "name": "name_CCC",
      "size": 3
    },
    {
      "name": "name_DDD",
      "size": 4
    }
  ]
}

I want to get following values with jq command.

name_AAA
name_BBB
name_CCC
name_DDD

I tried following but returned unexpected value.

$ jq -r '.group1[] * .group2[] | .name' < "mydata.json"
name_CCC
name_CCC
name_DDD
name_DDD

How can I get value which I wanted??

CodePudding user response:

You can use

jq -r '.[][].name' mydata.json

along with Raw Output option to get rid of wrapper quotes

Online Demo

CodePudding user response:

You might also wish to consider:

jq -r '..|.name?' mydata.json
  • Related