jQuery访问JSON对象

时间:2009-10-25 18:44:59

标签: jquery json

如何使用jQuery访问Object Literal中项目的名称?

例如,我如何阅读“标题”,“链接”,“媒体”等等...

{
    "title": "What we do in our free time...",
    "link": "http://www.flickr.com/photos/tnhimmies/4042938515/",
    "media": {"m":"http://farm3.static.flickr.com/2572/4042938515_3a00561320_m.jpg"},
    "date_taken": "2009-10-24T03:48:10-08:00",
    "description": "<p><a href=\"http://www.flickr.com/people/tnhimmies/\">Darlene, TN Persians (www.tnpurrs.com)<\/a> posted a photo:<\/p> <p><a href=\"http://www.flickr.com/photos/tnhimmies/4042938515/\" title=\"What we do in our free time...\"><img src=\"http://farm3.static.flickr.com/2572/4042938515_3a00561320_m.jpg\" width=\"240\" height=\"230\" alt=\"What we do in our free time...\" /><\/a><\/p> <p>Tennessee Persians<br /> <a href=\"http://www.tnpurrs.com\" rel=\"nofollow\">www.tnpurrs.com<\/a><\/p>",
    "published": "2009-10-25T18:28:36Z",
    "author": "nobody@flickr.com (Darlene, TN Persians (www.tnpurrs.com))",
    "author_id": "66405213@N00",
    "tags": "cat persian tnpurrs"
},

5 个答案:

答案 0 :(得分:21)

您还可以使用$.each功能:

var obj = { one:1, two:2, three:3, four:4, five:5 };

$.each(obj, function(key, value) {
  //..
});

如果您采用for...in语句方式,我建议您检查属性是否直接驻留在正在迭代的对象上,因为您可以some issues,如果Object.prototype已扩展:

for(var key in obj) {
  if (obj.hasOwnProperty(key)){
    // value = obj[key];
  }
}

答案 1 :(得分:9)

for (var key in json) {
  // ...
}

(这是标准的javascript,而不是jQuery特定的)

答案 2 :(得分:2)

在你的情况下,这根本不是一个数组!您想循环访问对象的属性。

JavaScript并不真正支持关联数组...请参阅http://www.hunlock.com/blogs/Mastering_Javascript_Arrays

Zed的回答很完美,我想补充一下

alert(json[key]);
如果你想知道如何获得属性的价值

,那么在for的内部

由于

答案 3 :(得分:0)

var testObject = {
    "title": "What we do in our free time...",
    "link": "http://www.flickr.com/photos/tnhimmies/4042938515/",
    "media": {"m":"http://farm3.static.flickr.com/2572/4042938515_3a00561320_m.jpg"},
    "date_taken": "2009-10-24T03:48:10-08:00",
    "description": "<p><a href=\"http://www.flickr.com/people/tnhimmies/\">Darlene, TN Persians (www.tnpurrs.com)<\/a> posted a photo:<\/p> <p><a href=\"http://www.flickr.com/photos/tnhimmies/4042938515/\" title=\"What we do in our free time...\"><img src=\"http://farm3.static.flickr.com/2572/4042938515_3a00561320_m.jpg\" width=\"240\" height=\"230\" alt=\"What we do in our free time...\" /><\/a><\/p> <p>Tennessee Persians<br /> <a href=\"http://www.tnpurrs.com\" rel=\"nofollow\">www.tnpurrs.com<\/a><\/p>",
    "published": "2009-10-25T18:28:36Z",
    "author": "nobody@flickr.com (Darlene, TN Persians (www.tnpurrs.com))",
    "author_id": "66405213@N00",
    "tags": "cat persian tnpurrs"
};

如果它是单个对象,那么你可以访问它   testObject.tags或testObject.title ......像这样

或者您可以按

进行迭代
$.each(obj,function(key,value){
///
});

答案 4 :(得分:0)

如果您愿意,可以在没有每个循环的情况下访问。

var obj = JSON.parse(data);
var title  = obj[0].title;