如何使用 jq 和 map 从复杂的键值对 JSON 中获取对象列表? (活动活动)
How to get object list from key value pairs complex JSON using jq and map? (Active Campaign)
我关注 JSON。我想根据他们的 CC 角色获取键值对对象。在此示例中,有 3 个角色(Presenter、Approver、Customer)。演示者的类型为 TO
。其他 2 个是 CC
类型。我想要 CC
类型。可以有更多,因为它是动态的。
JSON
{
"Presenter_TO_Email": "roney@domain.com",
"Approver_CC_Email": "tim@domain.com",
"Customer_CC_Email": "alex@domain.com",
"Invoice": "001",
"Date": "2022-02-14"
}
输出
{
"Approver": {
"email_address": "tim@domain.com",
"role": "Approver"
},
"Customer": {
"email_address": "alex@domain.com",
"role": "Customer"
}
}
我可以使用 this 示例来使用 INDEX,但是因为我使用的是旧版本 jq
,它会抛出错误 jq: error: INDEX/2 is not defined at <top-level>, line 1:
使用with_entries
根据键和值进行更改:
jq '
with_entries(
(.key / "_CC_") as $key | select($key[1])
| {key: $key[0], value: {email_address: .value, role: $key[0]}}
)
'
{
"Approver": {
"email_address": "tim@domain.com",
"role": "Approver"
},
"Customer": {
"email_address": "alex@domain.com",
"role": "Customer"
}
}
在包含 INDEX/2
的 jq 版本中,它被定义为一个简单的 jq 函数,因此如果您的 jq 不包含它,您可以自己简单地包含它的定义:
def INDEX(stream; idx_expr):
reduce stream as $row ({};
.[$row|idx_expr|
if type != "string" then tojson
else .
end] |= $row);
我关注 JSON。我想根据他们的 CC 角色获取键值对对象。在此示例中,有 3 个角色(Presenter、Approver、Customer)。演示者的类型为 TO
。其他 2 个是 CC
类型。我想要 CC
类型。可以有更多,因为它是动态的。
JSON
{
"Presenter_TO_Email": "roney@domain.com",
"Approver_CC_Email": "tim@domain.com",
"Customer_CC_Email": "alex@domain.com",
"Invoice": "001",
"Date": "2022-02-14"
}
输出
{
"Approver": {
"email_address": "tim@domain.com",
"role": "Approver"
},
"Customer": {
"email_address": "alex@domain.com",
"role": "Customer"
}
}
我可以使用 this 示例来使用 INDEX,但是因为我使用的是旧版本 jq
,它会抛出错误 jq: error: INDEX/2 is not defined at <top-level>, line 1:
使用with_entries
根据键和值进行更改:
jq '
with_entries(
(.key / "_CC_") as $key | select($key[1])
| {key: $key[0], value: {email_address: .value, role: $key[0]}}
)
'
{
"Approver": {
"email_address": "tim@domain.com",
"role": "Approver"
},
"Customer": {
"email_address": "alex@domain.com",
"role": "Customer"
}
}
在包含 INDEX/2
的 jq 版本中,它被定义为一个简单的 jq 函数,因此如果您的 jq 不包含它,您可以自己简单地包含它的定义:
def INDEX(stream; idx_expr):
reduce stream as $row ({};
.[$row|idx_expr|
if type != "string" then tojson
else .
end] |= $row);