簡體   English   中英

如果鍵具有動態值,如何使用 jq 過濾 json

[英]How to filter json with jq, if keys has dynamic value

我有 json:

    {
   "error": 0,
   "descErr": "Ok",
   "seqNumber": 0,
   "data": {
      "events": [],
      "devices": {
         "aaa1234a": {
            "deviceType": "aaa",
            "ip": "192.168.1.4",
            "otherInformation": "blabla4"
            },
         "aaa1235a": {
            "deviceType": "aaa",
            "ip": "192.168.1.5",
            "otherInformation": "blabla5"
            },
        "aaa1236a": {
            "deviceType": "aaa",
            "ip": "192.168.1.6",
            "otherInformation": "blabla6"
            }
         }
    }
}

並且只想獲取設備名稱(進入 json 看起來像 aaa1234a), ipotherInformation jq 我需要一個結果:

"aaa1234a": {
            "ip": "192.168.1.4",
            "otherInformation": "blabla4"
            },
"aaa1235a": {
            "ip": "192.168.1.5",
            "otherInformation": "blabla5"
            },
"aaa1236a": {
            "ip": "192.168.1.6",
            "otherInformation": "blabla6"
            }

如何使用 jq 過濾此 json,如果設備名稱我不知道,但看起來像“aaa1234a”,其中 aaa - 類型設備和最后一個“a” - model 設備 - 1234 - 動態名稱

https://jqplay.org/s/n1kf-19yFT

隨着輸入

{
   "error": 0,
   "descErr": "Ok",
   "seqNumber": 0,
   "data": {
      "events": [],
      "devices": {
         "aaa1234a": {
            "deviceType": "aaa",
            "ip": "192.168.1.4",
            "otherInformation": "blabla4"
            },
         "aaa1235a": {
            "deviceType": "aaa",
            "ip": "192.168.1.5",
            "otherInformation": "blabla5"
            },
        "aaa1236a": {
            "deviceType": "aaa",
            "ip": "192.168.1.6",
            "otherInformation": "blabla6"
            }
         }
    }
}

當我執行查詢時

.data.devices | to_entries | map({key, value: {ip: .value.ip, otherInformation: .value.otherInformation}}) | from_entries

我有 output

{
  "aaa1234a": {
    "ip": "192.168.1.4",
    "otherInformation": "blabla4"
  },
  "aaa1235a": {
    "ip": "192.168.1.5",
    "otherInformation": "blabla5"
  },
  "aaa1236a": {
    "ip": "192.168.1.6",
    "otherInformation": "blabla6"
  }
}

這是你所期待的嗎?

對於 select 匹配正則表達式模式“^aaa.*a$”的鍵,你可以寫:

.devices | with_entries(select(.key|test("^aaa.*a$")))

同樣,如果您想保留原始結構:

.data.devices |= with_entries(select(.key|test("^aaa.*a$")))

暫無
暫無

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

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