我有一个JSON数组,我想从(使用jq)中提取值:
这是一个简化的例子
{
"query": "",
"results": [
{
"id": 111,
...
"buyer": {
"email": "mail1@mail.com",
...
"billing_info": {
"doc_number": "123"
}
}
},
{
"id": 222,
...
"buyer": {
"email": "mail2@mail.com",
...
"billing_info": {
"doc_number": "456"
}
}
}
]
}
目前,我正在使用此过滤器:
{user: .results[].id, mail: .results[].buyer.email, buyer: .results[].buyer.billing_info.doc_number}
我正在进行全面加入"结果。
{"user":111,"mail":"mail1@mail.com","buyer":"123"}
{"user":111,"mail":"mail1@mail.com","buyer":"456"}
{"user":111,"mail":"mail2@mail.com","buyer":"123"}
{"user":111,"mail":"mail2@mail.com","buyer":"456"}
{"user":222,"mail":"mail1@mail.com","buyer":"123"}
{"user":222,"mail":"mail1@mail.com","buyer":"456"}
{"user":222,"mail":"mail2@mail.com","buyer":"123"}
{"user":222,"mail":"mail2@mail.com","buyer":"456"}
我想要的是从完整对象中过滤一些字段。所以在这个例子中,我有2个对象,所以我想要2个结果:
{"user":111,"mail":"mail1@mail.com","buyer":"123"}
{"user":222,"mail":"mail2@mail.com","buyer":"456"}
以下是我的示例摘录:
https://jqplay.org/s/nM1WzWRmnK
谢谢大家!
答案 0 :(得分:2)
你只需要将迭代器(.results[]
)“提升”到前面:
.results[]
| {user: .id, mail: .buyer.email, buyer: .buyer.billing_info.doc_number}
使用-c命令行选项,会产生:
{"user":111,"mail":"mail1@mail.com","buyer":"123"}
{"user":222,"mail":"mail2@mail.com","buyer":"456"}
将jq中的(ARRAY[] | ...)
视为与其他语言中的for (x in ARRAY) {...}
类似,可能会有所帮助。