gpt4 book ai didi

json - 如何使用 jq 过滤一组 json 对象?

转载 作者:行者123 更新时间:2023-12-04 10:17:30 25 4
gpt4 key购买 nike

我已经能够做到这一点。

json 输入,'data.json':

[
{
"Selected": null,
"Family Name": "Jones",
"Couple Name": "Jones, Adam & Rachael Margaret",
"Family Phone": "404-4477",
"Family Email": "email@sbcglobal.net",
"Family Address": "777 Aggies Court Kindly, California 95388 ",
"Head Of House Name": "Jones, Adam",
"Head Of House Phone": "(583) 404-2488",
"Head Of House Email": "email@sbcglobal.net",
"Spouse Name": "Jones, Rachael Margaret",
"Spouse Phone": null,
"Spouse Email": null,
"Child Name": null,
"Child Phone": null,
"Child Email": null
},
{
"Selected": "x",
"Family Name": "Xiong",
"Couple Name": "Xiong, Arlene Frances",
"Family Phone": null,
"Family Email": null,
"Family Address": "888 Walnut Ave. Blatant, California 95388 ",
"Head Of House Name": "Xiong, Arlene Frances",
"Head Of House Phone": "583-500-7917",
"Head Of House Email": "email@junk.net",
"Spouse Name": null,
"Spouse Phone": null,
"Spouse Email": null,
"Child Name": null,
"Child Phone": null,
"Child Email": null
},
{
"Selected": "x",
"Family Name": "Blair",
"Couple Name": "Blair, Toby & Silvia",
"Family Phone": "358-4645",
"Family Email": null,
"Family Address": "333 Cindy St. Stoic, California 95388 ",
"Head Of House Name": "Blair, Toby",
"Head Of House Phone": null,
"Head Of House Email": "email@stuff.net",
"Spouse Name": "Blair, Silvia",
"Spouse Phone": null,
"Spouse Email": null,
"Child Name": null,
"Child Phone": null,
"Child Email": null
}
]

我可以用它来过滤:
cat data.json | jq '.[] | select(.Selected != null) | {"Head Of House Name", "Head Of House Phone", "Head Of House Email", "Family Phone", "Family Email"}'

结果:
{
"Head Of House Name": "Xiong, Arlene Frances",
"Head Of House Phone": "583-500-7917",
"Head Of House Email": "email@junk.net",
"Family Phone": null,
"Family Email": null
}
{
"Head Of House Name": "Blair, Toby",
"Head Of House Phone": null,
"Head Of House Email": "email@stuff.net",
"Family Phone": "358-4645",
"Family Email": null
}

请注意,对象数组周围没有数组括号,对象之间也没有逗号……表示结果不是数组。

问题是结果不是对象数组(坦率地说,我不确定它是什么)。如何从一组 json 对象开始,过滤它们并最终得到一个过滤的对象列表?

最佳答案

当您使用过滤器时 .[] ,您实际上是将数组结果分解为每个项目的单独结果。您最终看到的是每个单独的结果,一个接一个。

为确保它们保留为数组,您可以通过用方括号包裹过滤器将结果放回数组中:

[
.[] |
select(.Selected != null) |
{
"Head Of House Name",
"Head Of House Phone",
"Head Of House Email",
"Family Phone",
"Family Email"
}
]

或者使用 map() 将其保留为数组过滤器,然后您可以删除 .[]部分:
map(
select(.Selected != null) |
{
"Head Of House Name",
"Head Of House Phone",
"Head Of House Email",
"Family Phone",
"Family Email"
}
)

如果你问我,你应该坚持 map() .

关于json - 如何使用 jq 过滤一组 json 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28458046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com