Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print nested values along with parent level values using jq

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}]'

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading