Home > other >  How to print nested values along with parent level values using jq
How to print nested values along with parent level values using jq

Time:05-19

I have the following json

{
    "data": [
        {
            "id": id1,
            "arr": [
                {
                    "arrId": arrId11,
                    "someOtherKey1": xxx,
                    "someOtherKey2": xxx,
                },
                {
                    "arrId": arrId12,
                    "someOtherKey1": xxx,
                    "someOtherKey2": xxx,
                }
            ],
            "otherParentLevelKey": yyyyy
        },
        {
            "id": id2,
            "arr": [
                {
                    "arrId": arrId21,
                    "someOtherKey1": xxx,
                    "someOtherKey2": xxx,
                },
                {
                    "arrId": arrId22,
                    "someOtherKey1": xxx,
                    "someOtherKey2": xxx,
                }
            ],
            "otherParentLevelKey": yyyyy
        }
    ]
}

And I want the following output

{
    "id": id1,
    "arr": [
        {
            "arrId": arrId11
        },
        {
            "arrId": arrId11
        }
    ]
}
{
    "id": id2,
    "arr": [
        {
            "arrId": arrId21
        },
        {
            "arrId": arrId21
        }
    ],
}

I tried the following query but it’s not syntactically correct

jsonArray | jq '.data[] | {id, arr[].arrId}'

The approach I am using right now is something like the below. The output is something I can manage but I was wondering if there is a way with jq to achieve the one I wanted above.

jsonArray | jq '.data[] | [{(.id): .arr[].arrId}]'

CodePudding user response:

Use a map to retain the array while modifying (here: reducing) it to your needs:

jq '.data[] | {id, arr: .arr | map({arrId})}'
{
  "id": "id1",
  "arr": [
    {
      "arrId": "arrId11"
    },
    {
      "arrId": "arrId12"
    }
  ]
}
{
  "id": "id2",
  "arr": [
    {
      "arrId": "arrId21"
    },
    {
      "arrId": "arrId22"
    }
  ]
}

Demo

  • Related