找到值为空字符串的对象键。

huangapple go评论59阅读模式
英文:

Find object keys with empty string values

问题

我正在尝试通过jq从以下JSON文件中获取名为key2且具有值""的键。

我正在使用Windows PowerShell中的jq。有人能帮助我吗?

{
    "Key": "value",
    "key1": "value1",
    "key2": ""
}
英文:

I'm trying to get the keys named key2 which has the value "" from a JSON file as below through jq.

I'm using jq in Windows PowerShell. Can someone please help me ?

{
    "Key": "value",
    "key1": "value1",
    "key2": ""
}

答案1

得分: 1

使用to_entries来获取键-值对的数组,然后使用.[]进行迭代,并使用select选择值为空的键-值对,最后提取键.key

to_entries[] | select(.value=="") | .key

输出:

"key2"

要在Windows PowerShell中运行,您可以将整个表达式用单引号括起来:

jq 'to_entries[] | select(.value=="") | .key'

至少根据PowerShell 7.3的文档建议的方法来看是可行的。

如果这种方法也不起作用,您可以将jq程序存储在一个文件中(例如,find-keys.jq,内容为 to_entries[] | select(.value=="") | .key),然后使用jq -f find-keys.jq加载它。

英文:

Use to_entries to get an array of key-value-pairs, then iterate it with .[] it and select the pairs with an empty value, and finally extract the .key from the pair:

to_entries[] | select(.value=="") | .key

Output:

"key2"

To run with Windows PowerShell, you should be able to quote the whole expression with single quotes:

jq 'to_entries[] | select(.value=="") | .key'

At least that's what the documentation of PowerShell 7.3 suggests.

If that does not work either, you can store your jq program in a file (e.g. find-keys.jq with content to_entries[] | select(.value=="") | .key) and then load it with jq -f find-keys.jq

huangapple
  • 本文由 发表于 2023年7月3日 17:27:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76603465-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定