[英]Flatten array for properties in nested array of JSON objects using jq
Having JSON with (simplified) Jira data like: 具有(简化的)Jira数据的JSON,例如:
{
"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. 注意:希望1)最后一个TEST-A
,2)前两个TEST-2
和TEST-3
,并希望3) TEST-2
和TEST-3
组合成一个数组。
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: 因此,需要进行两次维修才能达到所述目的:
(2) is dubious but easy to accomplish, eg using the helper function defined below. (2)是可疑的,但易于实现,例如使用下面定义的辅助函数。
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)})
If extract
should retain null
and false
values, then its def should be modified accordingly. 如果extract
应保留null
和false
值,则应相应修改其def。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.