【问题标题】:Not able to extract different array name from json file无法从 json 文件中提取不同的数组名称
【发布时间】:2020-02-05 06:21:41
【问题描述】:

我有多个如下所示的 JSON 文件。

{
  "09800214851900C3": {
    "label": "P7-R1-R16:S2",
    "name": "Geist Upgradable rPDU",
    "state": "normal",
    "order": 0,
    "type": "i03",
    "snmpInstance": 1,
    "lifetimeEnergy": "20155338",
    "outlet": {},
    "alarm": {
      "severity": "",
      "state": "none"
    },
    "layout": {
      "0": [
        "entity/total0",
        "entity/phase0",
        "entity/phase1",
        "entity/phase2"
      ]
    }
  }
}

从这里,我想使用 jq 像下面这样提取

09800214851900C3 : P7-R1-R16:S2

我遇到的问题是这个数组值 {09800214851900C3} 与所有 JSON 文件都不相同。所以我需要帮助来提取相同的内容。

【问题讨论】:

    标签: jquery arrays json


    【解决方案1】:

    基于数据格式,假设您需要对象中的第一个键及其标签值。
    使用Object.keys获取对象键,无需硬编码即可获取需要的值。

    const data = {
      "09800214851900C3": {
        "label": "P7-R1-R16:S2",
        "name": "Geist Upgradable rPDU",
        "state": "normal",
        "order": 0,
        "type": "i03",
        "snmpInstance": 1,
        "lifetimeEnergy": "20155338",
        "outlet": {},
        "alarm": {
          "severity": "",
          "state": "none"
        },
        "layout": {
          "0": [
            "entity/total0",
            "entity/phase0",
            "entity/phase1",
            "entity/phase2"
          ]
        }
      }
    };
    
    
    const extract = (key = Object.keys(data)[0], `${key} : ${data[key].label}`);
    
    console.log(extract)

    【讨论】:

    • 谢谢西瓦。但我想要使用 jq 查询的帮助
    【解决方案2】:

    我把它修好了。我使用下面的 jq 查询提取第一个键

    jsonfile.json | jq -r '.keys[]'
    

    基于此,我将键解析为另一个 jq 查询以获取标签值。

    jsonfile.json | jq -r '.09800214851900C3.label'
    

    【讨论】:

      猜你喜欢
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 2021-12-08
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多