【问题标题】:Parse multilevel JSON in JS [closed]在 JS 中解析多级 JSON [关闭]
【发布时间】:2018-09-23 12:01:48
【问题描述】:

我有这样的 JSON:

{
  "245": {
    "data": {
      "userData": {
        "id": "61",
        "image": "http://example.com",
        "name": "John Smith",
        "friends": [
          {
            "invited": "67"
          },
          {
            "invited": "62"
          },
          {
            "invited": "65"
          },
          {
            "invited": "66"
          }
        ],
        "operator": true
      }
    }
  }
}

我需要从中获取“id”值。第一个数字(“245”)总是不同的。

【问题讨论】:

  • 到目前为止,您尝试了哪些方法来解决问题?你的尝试有什么问题?
  • 如果您的问题是如何获取第一个始终会更改的数字,那么它与:getting the first index of an object 重复

标签: javascript json


【解决方案1】:

JSON.parse reviver parameter 可用于检查所有属性:

var id, json = '{"245":{"data":{"userData":{"id":"61","image":"http://example.com","name":"John Smith","friends":[{"invited":"67"},{"invited":"62"},{"invited":"65"},{"invited":"66"}],"operator":true}}}}'

var obj = JSON.parse(json, (key, val) => key == 'id' ? id = val : val)

console.log( id )

【讨论】:

    【解决方案2】:

    如果一直是这个结构,可以通过follow方法获取id:

    var obj = {
      "245": {
        "data": {
          "userData": {
            "id": "61",
            "image": "http://example.com",
            "name": "John Smith",
            "friends": [
              {
                "invited": "67"
              },
              {
                "invited": "62"
              },
              {
                "invited": "65"
              },
              {
                "invited": "66"
              }
            ],
            "operator": true
          }
        }
      }
    };
    var result = Object.entries(obj);
    console.log(result[0][1]["data"]["userData"]["id"])

    【讨论】:

      【解决方案3】:

      不确定您要寻找的最终输出是什么。您可以采取以下方法。如果你想要所有的键,id 对试试这个,其中数据是你的对象。

      const arr = [];
      Object.keys(data).forEach((key, index) => {
        arr.push({ key, id: data[key].data.userData.id });
      });
      console.log(arr);
      

      如果您只需要单个值,并且您确定对象结构总是有必需的键,请使用其中键为“245”的键。

      const id = data[key].data.userData.id
      

      如果你愿意,你也可以看看 lodash.get

      const id = _.get(data[key], "data.userData.id", "NA");
      

      https://lodash.com/docs/4.17.10#get

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-28
        • 1970-01-01
        • 2015-07-16
        • 1970-01-01
        • 1970-01-01
        • 2021-12-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多