我正在使用第三方API返回JSON对象。当我打印出变量时,我得到以下内容:
category:
{
"sys":
{
"id":"44uyBvGjFmsmoU6uqiiSOq",
"revision":1,
"type":"Entry",
"locale":"en-US",
"contentType":
{
"sys":
{
"id":"2V5tBa4wf6cuMSIu4McuUc",
"type":"Link",
"linkType":"ContentType"
}
},
"createdAt":"2014-09-13T22:40:39.901Z",
"updatedAt":"2014-09-13T22:40:39.901Z",
"space":
{
"sys":
{
"id":"t667fybp3v46",
"type":"Link",
"linkType":"Space"
}
}
},
"fields":
{
"name":"birth control"
}
}
但是当我尝试使用以下内容访问变量时,我继续得到“可能未处理的TypeError:无法读取未定义的属性'名称”:
if (o.fields.category)
{
var str = JSON.stringify(o.fields.category, undefined, 2);
console.log(str);
var json_category = JSON.parse(str);
// console.log("--------------Category for the resource: " + o.fields.category);
$.each(json_category, function(index, object){
alert(10);
var category = {};
// console.log("--------------Category for the resource: " + object.sys);
category.id = object.sys.id;
// console.log("--------------Category for the resource: " + object.fields.name);
category.name = object.fields.name;
// console.log("--------------Category for the resource: " + object.sys.updatedAt);
category.updatedAt = object.sys.updatedAt;
categories.push(category);
});
}
非常感谢任何帮助。
答案 0 :(得分:0)
将我的代码更改为以下内容。感谢Pointy提供的帮助,非常感谢。
if (o.fields.category)
{
console.log(o.fields.category.fields.name);
var category = {};
category.id = o.fields.category.sys.id;
category.name = o.fields.category.fields.name;
category.updatedAt = o.fields.category.sys.updatedAt;
categories.push(category);
}
record.categories = categories;
record.searchTags = search_tags;
records.push(record);