【问题标题】:How to filter json with jq, if keys has dynamic value如果键具有动态值,如何使用 jq 过滤 json
【发布时间】:2020-08-12 09:50:04
【问题描述】:

我有 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” - 型号设备 - 1234 - 动态名称

【问题讨论】:

  • jq '.data.devices' 有什么问题?

标签: json key jq


【解决方案1】:

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

我有输出

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

这是你所期待的吗?

【讨论】:

    【解决方案2】:

    要选择匹配正则表达式“^aaa.*a$”的键,你可以这样写:

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

    同样,如果你想保留原来的结构:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-29
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      相关资源
      最近更新 更多