jeudi 12 avril 2018

jq retain missing array objects from capturing group and update array

Input

[{
        "tags": [{
                "value": "domain:sourcing"
            },
            {
                "value": "apiname:src1"
            }
        ]
    },
    {
        "tags": [{
            "value": "apiname:fin1"
        }]
    },
    {
        "tags": [{
            "value": "domain:fin1"
        }]
    }
]

Expected output

[{
        "domain": "sourcing",
        "apiname": "src1"
    },
    {
        "domain": "-",
        "apiname": "fin1"
    },
    {
        "domain": "fin1",
        "apiname": "-"
    }
]

So far I have tried below.

jq 'map(. + (.tags[].value | capture("domain:(?<domain>.+)"))) | map(. + (.tags[].value | capture("apiname:(?<apiname>.+)"))) | map(del(.tags))'

partial output from above cmd

[
  {
    "apiDomain": "sourcing",
    "apiName": "src1"
  }
]

As you have seen, the problem here is I'm completely loosing the other objects if any one capturing group filed is absent. Second object in input has apiname but missing "domain" and third object has "domain" but missing "apiname". As stated in the sample output, if any object doesn't present, then they should come as "-".

Can the jq command be updated to achieve this please?

Aucun commentaire:

Enregistrer un commentaire