简体   繁体   中英

Flatten array for properties in nested array of JSON objects using jq

Having JSON with (simplified) Jira data like:

{
    "issues": [
        {
            "key": "TEST-A",
            "fields": { "issuelinks": [] }
        },
        {
            "key": "TEST-B",
            "fields": {
                "issuelinks": [
                    { "inwardIssue": { "key": "TEST-1" } },
                    { "outwardIssue": { "key": "TEST-2" } },
                    { "outwardIssue": { "key": "TEST-3" } }
                ]
            }
        }
    ]
}

Would like to get output like:

[
    { "key": "TEST-A", "inward": null, "outward": null },
    { "key": "TEST-B", "inward": ["TEST-1"], "outward": ["TEST-2", "TEST-3"] }
]

Tried (ignoring the inward links for now):

cat data.json | \
jq '.issues[] | {"key":.key, "outward":.fields.issuelinks[].outwardIssue.key }'

But I get:

{ "key": "TEST-B", "outward": "TEST-1" }
{ "key": "TEST-B", "outward": "TEST-2" }
{ "key": "TEST-B", "outward": null }

Note: would expect 1) TEST-A for the last one, 2) TEST-2 and TEST-3 for the first two and would like to 3) have TEST-2 and TEST-3 combined in an array.

Suggestions?

Let's start with a variation of your first attempt:

.issues[]
 | {key,
   inward: .fields.issuelinks|map(.inwardIssue.key // empty),
   outward: .fields.issuelinks|map(.outwardIssue.key // empty) }

With your example, this produces:

{"key":"TEST-A","inward":[],"outward":[]}
{"key":"TEST-B","inward":["TEST-1"],"outward":["TEST-2","TEST-3"]}

So two repairs are needed to achieve the stated goal:

  1. Produce an array (eg, by wrapping the above expression in square brackets)
  2. Replace the empty arrays by null.

(2) is dubious but easy to accomplish, eg using the helper function defined below.

Solution

def extract(f): map(f // empty) | if length ==0 then null else . end;

.issues
| map(
   {key,
    inward: .fields.issuelinks|extract(.inwardIssue.key),
    outward: .fields.issuelinks|extract(.outwardIssue.key)})

Caveat

If extract should retain null and false values, then its def should be modified accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM