-4

我有这样的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”)总是不同的。

4

3 回答 3

2

JSON.parsereviver 参数可用于检查所有属性:

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 )

于 2018-09-23T12:29:07.363 回答
1

如果它始终具有这种结构,您可以通过以下方法获取 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"])

于 2018-09-23T12:19:22.043 回答
0

不确定您要寻找的最终输出是什么。您可以采取以下方法。如果你想要所有的键,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

于 2018-09-23T12:13:43.957 回答