【问题标题】:Skip non-array attributes at a specific nesting level in JSON跳过 JSON 中特定嵌套级别的非数组属性
【发布时间】:2020-06-21 00:26:05
【问题描述】:

我正在尝试从 the source list it uses 检索 Firefox 的黑名单主机,以便将其用于另一个浏览器 (Qutebrowser)。

我已经相当成功地使用jq 解析 JSON。

#!/bin/sh
for term in Advertising Content Social Analytics Fingerprinting Cryptomining Disconnect; do
    jq ".categories.$term[][][][]" services.json
done

但是,某些类别的一些最深的对象(始终处于同一嵌套级别)包含破坏jq 的额外信息,例如下面的"performance": "true"

{
  "categories": {
    ...
    "Cryptomining": [
      {
        "a.js": {
          "http://zymerget.bid": [
            "alflying.date",
            "alflying.win",
            ...
            "zymerget.faith"
          ],
          "performance": "true"
        }
      },
      {
        "CashBeet": {
          "http://cashbeet.com": [
            "cashbeet.com",
            "serv1swork.com"
          ]
        }
      },
      ...

因此,例如,当循环到达 jq ".categories.Cryptomining[][][][]" services.json 时,它会引发错误并停止处理类别:

"alflying.date"
"alflying.win"
...
"zymerget.faith"
jq: error (at servicesN.json:11167): Cannot iterate over string ("true")

有什么方法可以忽略jq 的那些非数组属性?作为一个额外,请让我知道我是否可以放弃 for 循环并在单个 jq 中完成整个过程(因为目前,如上所示,我在for 循环)。

【问题讨论】:

    标签: json bash sh jq


    【解决方案1】:

    有什么方法可以忽略jq 的那些非数组属性?

    是的,arrays built-in

    作为一个额外的,请告诉我是否可以放弃 for 循环并在单个 jq 中完成整个过程(因为目前,如上所示,我列出了所有for 循环中的类别)。

    Array/Object Value Iterator 为你做这件事。

    jq '.categories[][][][] | arrays[]' services.json
    

    但是,对于这个特定的任务,您似乎根本不需要arrays;以下命令产生相同的输出:

    jq '.categories[][][][][]?' services.json
    

    .[]?

    【讨论】:

      【解决方案2】:

      给定

      {
        "categories": {
          "Cryptomining": [
            {
              "a.js": {
                "http://zymerget.bid": [
                  "alflying.date",
                  "alflying.win",
                  "zymerget.faith"
                ],
                "performance": "true"
              }
            },
            {
              "CashBeet": {
                "http://cashbeet.com": [
                  "cashbeet.com",
                  "serv1swork.com"
                ]
              }
            }
          ]
        }
      }
      

      作为嵌套路径的替代方案,您可以使用递归下降:

      .. | strings
      

      产生:

      "alflying.date"
      "alflying.win"
      "zymerget.faith"
      "true"
      "cashbeet.com"
      "serv1swork.com"
      

      要排除“true”,请将其设为布尔值排除其中没有 . 的字符串:

      .. | strings | select(contains("."))
      

      返回:

      "alflying.date"
      "alflying.win"
      "zymerget.faith"
      "cashbeet.com"
      "serv1swork.com"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-05
        • 2020-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-22
        相关资源
        最近更新 更多