使用 jq 过滤空 and/or 空值

Filter empty and/or null values with jq

我有一个包含 jsonlines 的文件,我想查找空值。

{"name": "Color TV", "price": "1200", "available": ""}
{"name": "DVD player", "price": "200", "color": null}

并想输出空的 and/or 个空值及其键:

available: ""
color: null

我认为它应该类似于 cat myexample | jq '. | select(. == "")',但它不起作用。

这里棘手的部分是以空字符串用引号显示的方式发出不带引号的键。这是一种与 jq 的 -r command-line 选项一起使用的解决方案:

to_entries[]
| select(.value | . == null or . == "")
| if .value == "" then .value |= "\"\(.)\"" else . end
| "\(.key): \(.value)"

一旦以明显的方式修改了给定的输入使其有效JSON,输出就完全符合指定。

有些人可能会发现以下 jq 程序对于识别具有 null 或空字符串值的键更有用:

with_entries(select(.value |.==null or . == ""))

使用示例输入,该程序将生成:

{"available":""}
{"color":null}

添加更多信息,例如输入行或对象编号,也是有意义的,例如也许:

with_entries(select(.value |.==null or . == ""))
| select(length>0)
| {n: input_line_number} + .