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

Extract child key and flatten into parent object output in JQ

I’m trying to simplify a nested JSON structure using JQ

Input

[
  {
    "defaultBranchRef": {
      "name": "main"
    },
    "nameWithOwner": "KyleMit/stack-posts"
  },
  {
    "defaultBranchRef": {
      "name": "master"
    },
    "nameWithOwner": "KyleMit/HelloSERN"
  }
]

Desired Output

[
  {
    "nameWithOwner": "KyleMit/stack-posts",
    "defaultBranchName": "main"
  },
  {
    "nameWithOwner": "KyleMit/HelloSERN",
    "defaultBranchName": "master"
  }
]

Attempted Solution

I can retrieve each of the individual fields at any depth

  • Get nameWithOwner

    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

    [.[]|.nameWithOwner] // ["KyleMit/stack-posts","KyleMit/HelloSERN"]
    
  • Get defaultBranchRef.name

    [.[]|.defaultBranchRef.name] // ["main","master"]
    

But can’t quite get how to combine fields / selectors to return mulitple values

>Solution :

Just update |= the defaultBranchRef field to the content of its name subfield:

jq '.[].defaultBranchRef |= .name'
[
  {
    "defaultBranchRef": "main",
    "nameWithOwner": "KyleMit/stack-posts"
  },
  {
    "defaultBranchRef": "master",
    "nameWithOwner": "KyleMit/HelloSERN"
  }
]

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