Given this input:

[
  {
    "Id": "cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b",
    "Names": [
      "condescending_jones",
      "loving_hoover"
    ]
  },
  {
    "Id": "186db739b7509eb0114a09e14bcd16bf637019860d23c4fc20e98cbe068b55aa",
    "Names": [
      "foo_data"
    ]
  },
  {
    "Id": "a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19",
    "Names": [
      "jovial_wozniak"
    ]
  },
  {
    "Id": "76b71c496556912012c20dc3cbd37a54a1f05bffad3d5e92466900a003fbb623",
    "Names": [
      "bar_data"
    ]
  }
]

I'm trying to construct a filter with jq that returns all objects with Ids that do not contain "data" in the inner Names array, with the output being newline-separated. For the above data, the output I'd like is:

cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19

我想我有点接近这一点了:

(. - select(.Names[] contains("data"))) | .[] .Id

but the select filter is not correct and it doesn't compile (get error: syntax error, unexpected IDENT).

推荐答案

非常接近!在select表达式中,必须在contains之前使用管道(|).

This filter produces the expected output.

. - map(select(.Names[] | contains ("data"))) | .[] .Id

The jq Cookbook has an example of the syntax.

Filter objects based on the contents of a key

例如,我只想要类型键包含"house"的对象.

$ json='[{"genre":"deep house"}, {"genre": "progressive house"}, {"genre": "dubstep"}]'
$ echo "$json" | jq -c '.[] | select(.genre | contains("house"))'
{"genre":"deep house"}
{"genre":"progressive house"}

Colin D询问如何保留数组的JSON struct ,以便最终输出是单个JSON数组,而不是JSON对象流.

最简单的方法是将整个表达式包装在数组构造函数中:

$ echo "$json" | jq -c '[ .[] | select( .genre | contains("house")) ]'
[{"genre":"deep house"},{"genre":"progressive house"}]

您还可以使用映射功能:

$ echo "$json" | jq -c 'map(select(.genre | contains("house")))'
[{"genre":"deep house"},{"genre":"progressive house"}]

map解压输入数组,将过滤器应用于每个元素,并创建一个新array.换句话说,map(f)等于[.[]|f].

Json相关问答推荐

中间初始化的Jolt配置

如何使用Aeson解码带有Unicode字符的JSON文件?

在AWS步骤函数中将字符串解析为JSON&S映射状态

VBA json按特定属性名称提取所有数据

JQ:获取该值的较短语法是什么

无法访问id的第三级json

(已回答)JSON 读取函数返回未定义而不是预期值 - Typescript

如何对未知/变量键的字典进行编码?

Vega-Lite规范:尽管在规范中提供了数据,但显示空图表

Jolt 不打印任何东西

JSON 的自定义编组器,可以是字符串或 map[string]string / map[string]bool

jq可以在两个JSON对象列表中依次添加对象吗?

传统编程语言等价于动态 SQL

Jolt - 在同一级别添加时组合值的问题

缺少所需的请求正文内容:org.springframework.web.method.HandlerMethod$HandlerMethodParameter

如何判断 Json 对象中是否存在键并获取其值

一起使用 Argparse 和 Json

从 HttpResponse 获取 json

Java JSON 序列化 - 最佳实践

Rails 中奇怪的 JSON Javascript 问题