【发布时间】:2014-09-15 18:47:41
【问题描述】:
我正在使用第 3 方 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"
}
}
但是当我尝试使用以下方法访问变量时,我不断收到“可能未处理的类型错误:无法读取未定义的属性‘名称’”:
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);
});
}
非常感谢任何帮助。
【问题讨论】:
-
您对该 API 的调用是什么样的?问题很可能是您的 API 是异步的,并且您没有正确等待结果。
-
我正在使用 Contentful 和他们的 Javascript 库 contentful.com/developers/documentation/content-delivery-api
-
这很难说;从 inside 调试到
$.each()循环的回调会更有用。您不必对对象进行字符串化来记录它;使用console.dir(object);,您将能够在开发者控制台中检查该对象。 -
只需将
alert(10)调用替换为console.log("index: " + index + " object: ", object);并打开浏览器开发者控制台。 (“控制台”选项卡;开发者控制台现在有很多东西。) -
你不能直接使用'category.sys.id'而不是'category.id'来访问id,name也是一样。
标签: javascript json getjson