我正在尝试通过 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"
]
}
我在返回“regular-title”和“regular-body”时遇到问题。
我的 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
}
我假设这是因为 posts[eachPost].regular-title 中有破折号,但我找不到任何关于如何让它在这种情况下工作的文档!
谢谢。
最佳答案
在您的示例中,javascript 变量名称不能包含特殊字符,例如 -
。如果您有一个名称中包含特殊字符的属性,访问它的唯一方法是使用您用来访问上面的 posts
对象的 []
方法,它为您提供了一个将属性名称作为字符串传递的选项。
var regularTitle = posts[eachPost]['regular-title'];
关于javascript - 使用 javascript 获取 JSON 数据(来自 Tumblr),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5045152/