我正在尝试通过JSON API阅读Tumblr帖子。
使用他们的API,数据会像这样传回:
var tumblr_api_read= {
"posts":[
"id":"1234",
"regular-title":"This is the title of the post",
"regular-body":"This is the body of the post"
]
}
我无法返回“常规标题”和“常规标题”。
我的JS代码如下所示:
var tumblr= tumblr_api_read['posts'];
for (eachPost in tumblr)
{
var id=posts[eachPost].id; //Works fine
var regularTitle=posts[eachPost].regular-title; //Returns NaN
}
我假设这是因为帖子[eachPost] .sters-title中有短划线但是在这种情况下我找不到任何关于如何使其工作的文档!
感谢。
答案 0 :(得分:5)
javascript变量名称不能包含示例中的-
等特殊字符。如果您的名称中包含特殊字符的属性,则访问它的唯一方法是使用您用于访问上面[]
对象的posts
方法,该方法可以选择将属性名称作为字符串。
var regularTitle = posts[eachPost]['regular-title'];
答案 1 :(得分:1)
进一步详细说明,您实际上是以点表示法引用regular-title
,就像它是一个对象一样。但它实际上是一个数组,这就是为什么即使属性值没有如上所述的破折号也无法工作。