如何从JSON对象检索属性?

时间:2017-06-02 22:18:14

标签: jquery json

这是我的JSON对象,通过AJAX接收。

{
    "results": [
        {
            "picture": {
                "large": "https://randomuser.me/api/portraits/women/50.jpg",
                "medium": "https://randomuser.me/api/portraits/med/women/50.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/women/50.jpg"
            }
        }
    ],
    "info": {
        "seed": "8f0630cfc3b5e88c",
        "results": 1,
        "page": 1,
        "version": "1.1"
    }
}

如何记录其中一个图片属性的网址?

我确实尝试了console.log(data.hasOwnProperty(data["results.picture.large"]));,但这会返回false

3 个答案:

答案 0 :(得分:0)

希望这可以解释你不清楚的一切。



var data = {
  "results": [{
    "picture": {
      "large": "https://randomuser.me/api/portraits/women/50.jpg",
      "medium": "https://randomuser.me/api/portraits/med/women/50.jpg",
      "thumbnail": "https://randomuser.me/api/portraits/thumb/women/50.jpg"
    }
  }],
  "info": {
    "seed": "8f0630cfc3b5e88c",
    "results": 1,
    "page": 1,
    "version": "1.1"
  }
};

var results = data.results;
var result = results[0];
var picture = result.picture;
var large = picture.large;

console.log(data.hasOwnProperty('results'));
console.log(result.hasOwnProperty('picture'));
console.log(picture.hasOwnProperty('large'));
console.log(data.results[0].picture.large === large);
console.log(data.results[0].picture.large);




答案 1 :(得分:0)

由于结果是一个数组,我们必须指定数组索引,如下所示: data.results[0].picture.large

var data = {
    "results": [
        {
            "picture": {
                "large": "https://randomuser.me/api/portraits/women/50.jpg",
                "medium": "https://randomuser.me/api/portraits/med/women/50.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/women/50.jpg"
            }
        }
    ],
    "info": {
        "seed": "8f0630cfc3b5e88c",
        "results": 1,
        "page": 1,
        "version": "1.1"
    }
}

console.log(data.results[0].picture.large);

答案 2 :(得分:0)

让我们假设你通过ajax收到你的json数据并将其保存在一个名为data的变量中。你可以像这样访问它。

这是缩略图img:data ["结果"] [0] ["图片"] ["缩略图"]

这适用于中型img:数据["结果"] [0] ["图片"] ["中"]

这适用于大型img:数据["结果"] [0] ["图片"] ["大"]

你可能想知道这是如何工作的。

var data = {
   "johnlee123" : {
      "address" : "123 s adam st",
      "zipcode" : 43924
   },
   "julie234" : {
      "address" : "234 n sachel st",
      "zipcode" : 34567
   }
};

如果你访问这些数据[" johnlee123"]它会给你这个

{
  "address" : "123 s adam st",
  "zipcode" : 43924
}

如果你访问这些数据[" johnlee123"] ["地址"]它会给你回复

"123 s adam st"