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

戴维·韦扎尼

我已经能够做到这一点。

json输入,“ data.json”:

[
  {
    "Selected": null,
    "Family Name": "Jones",
    "Couple Name": "Jones, Adam & Rachael Margaret",
    "Family Phone": "404-4477",
    "Family Email": "[email protected]",
    "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 protected]",
    "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 protected]",
    "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 protected]",
    "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 protected]",
  "Family Phone": null,
  "Family Email": null
}
{
  "Head Of House Name": "Blair, Toby",
  "Head Of House Phone": null,
  "Head Of House Email": "[email protected]",
  "Family Phone": "358-4645",
  "Family Email": null
}

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

问题在于结果不是对象数组(坦率地说,我不确定它是什么)。我怎样才能从一个json对象数组开始,对其进行过滤,最后得到一个过滤对象列表?

杰夫·梅卡多(Jeff Mercado)

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

为了确保将它们保存为数组,您可以使用方括号将过滤器包装起来,从而将结果放回数组中:

[
    .[] |
    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()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章