簡體   English   中英

使用 jq 查找嵌套的 JSON 對象

[英]Find nested JSON objects using jq

有沒有辦法使用 jq 在高度嵌套的 JSON 文件中查找特定對象的位置和值?

我永遠不知道它們會在 JSON 的結構中出現在哪里,我也不知道父母的名字。 我只知道我正在搜索的 object 的名稱。

例如,我試圖找到“FIND_ME”對象在以下 JSON 中的位置,與整個 JSON 結構相關,但也包括“FIND_ME”中包含的值。 所以對於這個 JSON:

{
    "system": {
        "operating_system_1": {
            "FIND_ME": {
                "special_detail_1": "some_detail",
                "special_detail_2": "some_detail"
            },
            "feature_1": {
                "detail_1": "some_detail"
            },
            "feature_2": {
                "detail_2": "some_detail"
            }
        },
        "operating_system_2": {
            "feature_1": {
                "FIND_ME": {
                    "special_detail_3": "some_detail",
                    "special_detail_4": "some_detail"
                },
                "detail_3": "some_detail"
            },
            "feature_2": {
                "detail_4": "some_detail"
            }
        },
        "operating_system_3": {
            "feature_1": {
                "detail_5": "some_detail"
            },
            "feature_2": {
                "detail_6": "some_detail"
            }
        }
    }
}

理想情況下,我會得到以下 output:

{
    "system": {
        "operating_system_1": {
            "FIND_ME": {
                "special_detail_1": "some_detail",
                "special_detail_2": "some_detail"
            }
        },
        "operating_system_2": {
            "feature_1": {
                "FIND_ME": {
                    "special_detail_3": "some_detail",
                    "special_detail_4": "some_detail"
                }
            }
        }
    }
}

這樣我就可以檢查大量文件以確保“FIND_ME”沒有出現在不應該出現的地方,從而導致錯誤。 我從其他問題中嘗試了以下內容:

cat json_file | jq '..|.FIND_ME? | select(. != null)'

它給出了“FIND_ME”的值,像這樣

{
  "special_detail_1": "some_detail",
  "special_detail_2": "some_detail"
}
{
  "special_detail_3": "some_detail",
  "special_detail_4": "some_detail"
}

但它不顯示父結構。

嘗試

jq --arg query "FIND_ME" '
  reduce ((paths | select(.[-1] == $query)) as $p | [$p, getpath($p)])
    as $f ({}; setpath($f[0]; $f[1]))
' json_file
{
  "system": {
    "operating_system_1": {
      "FIND_ME": {
        "special_detail_1": "some_detail",
        "special_detail_2": "some_detail"
      }
    },
    "operating_system_2": {
      "feature_1": {
        "FIND_ME": {
          "special_detail_3": "some_detail",
          "special_detail_4": "some_detail"
        }
      }
    }
  }
}

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM