使用 JQ“包含”并在未找到密钥时抑制错误

mfa*_*aiz 3 shell json try-catch jq

我试图根据同一对象中另一个键的“包含”值来获取值

我已经尝试了一个代码,它可以工作并输出我想要的结果,但是 JSON 中的某些对象没有这个键,因此我得到:

jq: error (at <stdin>:1): null (null) and string ("BBC") cannot have their containment checked

或者这个错误的原因是其他键中的数组,我不确定

使用:

jq '.entries[] | select(.icon | contains("BBC")) | .uuid'

我希望找到的结果的 UUID 没有错误,并将其作为变量存储在 shell 中

"174501xxxxxxxxxxxxxe6342a03"

通过管道传输的输入文件

{  
   "entries":[  
      {  
         "uuid":"174501xxxxxxxxxxxxxe6342a03",
         "enabled":true,
         "autoname":true,
         "name":"BBC",
         "number":0,
         "icon":"file:///logos/BBC.png",
         "icon_public_url":"imagecache/1097",
         "epgauto":true,
         "epggrab":[  ],
         "dvr_pre_time":0,
         "dvr_pst_time":0,
         "epg_running":-1,
         "services":[  ],
         "tags":[  ],
         "bouquet":""
      },
      {  
         "uuid":"174501xxxxxxxxxxxxxe6342a04",
         "enabled":true,
         "autoname":true,
         "name":"ABC",
         "number":0,
         "icon_public_url":"imagecache/1098",
         "epgauto":true,
         "epggrab":[  ],
         "dvr_pre_time":0,
         "dvr_pst_time":0,
         "epg_running":-1,
         "services":[  ],
         "tags":[  ],
         "bouquet":""
      }...
Run Code Online (Sandbox Code Playgroud)

AKs*_*tat 5

使用 jq 有不止一种方法可以实现这一点。您可以使用条件和分支,但我认为最简单的方法是使用try-catch而无需catch沉默任何错误。该文档位于条件和比较的末尾

这是一个示例,它会简单地忽略错误并且仅在该对象没有错误时才打印 UUID:

.entries[] | select(.icon | try contains("BBC")) | .uuid

  • 你可以使用 `contains("BBC")?` 作为 `try contains("BBC")` 的同义词。 (2认同)

mic*_*ckp 5

您只能预先选择具有 的icon键的对象has("icon")

来自jq 1.5 手册

has(key)

内置函数has返回输入对象是否具有给定键,或者输入数组是否在给定索引处具有元素。

jq '.entries[] | select(has("icon")) | select(.icon | contains("BBC")).uuid' file
Run Code Online (Sandbox Code Playgroud)

"icon":null但是,如果您的对象有这种情况,它会输出错误,您可以使用:

jq '.entries[] | select(.icon != null) | select(.icon | contains("BBC")).uuid' file
Run Code Online (Sandbox Code Playgroud)