如何使用JQ和MAP从复杂的JSON中获取对象的键值对?(活动活动) [英] How to get key value pairs of the objects from complex JSON using jq and map? (Active Campaign)
本文介绍了如何使用JQ和MAP从复杂的JSON中获取对象的键值对?(活动活动)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我关注了JSON。我想根据角色获取键-值对对象。在本例中,有3个角色(演示者、审批者、客户),但可以有更多角色,因为它是动态的。
JSON
{
"Presenter Name": "Roney",
"Presenter Email": "roney@domain.com",
"Approver Name": "Tim",
"Approver Email": "tim@domain.com",
"Customer Name": "Alex",
"Customer Email": "alex@domain.com",
"Invoice": "001",
"Date": "2022-02-14"
}
使用JQ、MAP的预期输出
{
"Presenter": {
"email_address": "roney@domain.com",
"name": "Roney",
"role": "Presenter"
},
"Approver": {
"email_address": "tim@domain.com",
"name": "Tim",
"role": "Approver"
},
"Customer": {
"email_address": "alex@domain.com",
"name": "Alex",
"role": "Customer"
}
}
我一直在追随,但不知道下一步该做什么。请指教。
to_entries |map( { (.key): { name: .value, email_address:.value, role: .key} } ) | add
推荐答案
这里有一个更短的方法,它不使用group_by
。相反,这将使用reduce
直接迭代初始对象,并且如果键遵循空格分隔的角色-键模式,则立即相应地设置所有字段。
reduce (to_entries[] | .key /= " ") as {key: [$role, $key], $value} ({};
if $key then
.[$role] += {({Email: "email_address", Name: "name"}[$key]): $value, $role}
else . end
)
{
"Presenter": {
"name": "Roney",
"role": "Presenter",
"email_address": "roney@domain.com"
},
"Approver": {
"name": "Tim",
"role": "Approver",
"email_address": "tim@domain.com"
},
"Customer": {
"name": "Alex",
"role": "Customer",
"email_address": "alex@domain.com"
}
}
这篇关于如何使用JQ和MAP从复杂的JSON中获取对象的键值对?(活动活动)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文