javascript - 使用 javascript 获取 JSON 数据(来自 Tumblr)

标签 javascript json tumblr

我正在尝试通过 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/

相关文章:

javascript - 转换为货币格式

javascript - html partials 中的样式标签

HashMap<String,LinkedList<Investor>> 的 java jackson 数据绑定(bind)

javascript - 使用 Tumblr API 从帖子标题中提取第一句话

jquery - 尽管使用了 desandro 和新的 jquery,但 tumblr masonry + 无限滚动重叠帖子

javascript - 使 HTML 表格中的所有列都可编辑,只有一列除外

HTML 表格单元格中的 Javascript 函数调用

android - 当我使用 JSONParser (httpurlconnection) 运行我的 android 登录 Activity 时出现异常

php - 将 json_decode 数据从最旧到最新存储在 MySql 数据库中

css - 自定义 Tumblr *新* 点赞按钮 iFrame {LikeButton}