JSON - 如何在纯JS中获得价值

时间:2016-11-06 21:40:08

标签: javascript arrays json object

我无法从我的JSON对象中获取任何值。

我在尝试:

console.log(players[0].player.info.position)

它返回undefined。 我做错了什么?

验证器说JSON有效。 这是JSON对象:

{"players": [
{
  "player": {
    "info": {
      "position": "aaa",
      "shirtNum": 1,
      "positionInfo": "aaa"
    },
    "nationalTeam": {
      "isoCode": "aaa",
      "country": "aaa",
      "demonym": "aaa"
    },
    "age": "221",
    "name": {
      "first": "aaa",
      "last": "aaa"
    },
    "id": 111,
    "currentTeam": {
      "name": "aaa",
      "teamType": "aaa",
      "shortName": "aaa",
      "id": 21
    }
  }
}]}

3 个答案:

答案 0 :(得分:0)

试试JSON.parse()。 JSON本身就是一个字符串。

obj = JSON.parse('{"players":[{"player":{"info":{"position":"aaa","shirtNum":1,"positionInfo":"aaa"},"nationalTeam":{"isoCode":"aaa","country":"aaa","demonym":"aaa"},"age":"221","name":{"first":"aaa","last":"aaa"},"id":111,"currentTeam":{"name":"aaa","teamType":"aaa","shortName":"aaa","id":21}}}]}');

console.log(obj['players'][0].player.info.position);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

答案 1 :(得分:0)

将JSON.parse与json字符串一起使用:

obj = JSON.parse('{"players":[{"player":{"info":{"position":"aaa","shirtNum":1,"positionInfo":"aaa"},"nationalTeam":{"isoCode":"aaa","country":"aaa","demonym":"aaa"},"age":"221","name":{"first":"aaa","last":"aaa"},"id":111,"currentTeam":{"name":"aaa","teamType":"aaa","shortName":"aaa","id":21}}}]}');

console.log(obj['players'][0].player.info.position);
              

答案 2 :(得分:0)

你可能在我称之为theThing的变量中有json。您需要使用theThing来访问您的json。

var theThing =    JSON.parse('{"players":[{"player":{"info":{"position":"aaa","shirtNum":1,"positionInfo":"aaa"},"nationalTeam":{"isoCode":"aaa","country":"aaa","demonym":"aaa"},"age":"221","name":{"first":"aaa","last":"aaa"},"id":111,"currentTeam":{"name":"aaa","teamType":"aaa","shortName":"aaa","id":21}}}]}');
alert(theThing.players[0].player.info.position);