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

时间:2015-02-11 15:26:04

标签: json jq

我能够做到这一点。

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对象开始,过滤它们并最终得到一个过滤的对象列表?

1 个答案:

答案 0 :(得分:13)

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

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

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