【发布时间】:2015-09-23 16:12:51
【问题描述】:
我有一个 drupal 网站,在该网站上创建文章,然后以 JSON 格式输出到特定链接。我目前正在尝试解析 JSON 并保存 Parse Core 上文章的标题、正文等。 JSON 输出示例:
[
{
"vid": "2",
"uid": "1",
"title": "Post 2",
"log": "",
"status": "1",
"comment": "0",
"promote": "1",
"sticky": "0",
"nid": "2",
"type": "article",
"language": "und",
"created": "1435932743",
"changed": "1436089990",
"tnid": "0",
"translate": "0",
"revision_timestamp": "1436089990",
"revision_uid": "1",
"body": {
"und": [
{
"value": "Integer at mi blandit ipsum malesuada consectetur...",
"summary": "",
"format": "plain_text",
"safe_value": "<p>Integer at mi blandit ipsum malesuada consectetur...</p>\n",
"safe_summary": ""
}
]
},
"field_tags": [],
"field_image": [],
"name": "uknj",
"picture": "0",
"data": "b:0;"
},
{
"vid": "1",
"uid": "1",
"title": "Sample Post",
"log": "",
"status": "1",
"comment": "0",
"promote": "1",
"sticky": "0",
"nid": "1",
"type": "article",
"language": "und",
"created": "1435931896",
"changed": "1436090000",
"tnid": "0",
"translate": "0",
"revision_timestamp": "1436090000",
"revision_uid": "1",
"body": {
"und": [
{
"value": "Lorem ipsum dolor sit amet...",
"summary": "",
"format": "plain_text",
"safe_value": "<p>Lorem ipsum dolor sit amet...</p>\n",
"safe_summary": ""
}
]
},
"field_tags": [],
"field_image": [],
"name": "uknj",
"picture": "0",
"data": "b:0;"
}
]
我的代码部分基于this github。但是,由于 body 对象包含一个数组,我无法进一步解析它,并且包含我想要的文本的直接 body-value 无法保存。
我查看了this Stackoverflow question 仍然无法解决问题。正在返回错误 Cannot read property 'length' of undefined。值得注意的是,vid和title都保存成功了。
此外,仅记录了其中一个帖子,带有"vid" : "2" 的帖子,不知道为什么它不存储另一个帖子。
我的 main.js 代码:
var _ = require("underscore");
Parse.initialize('xyz', '123');
var Articles = Parse.Object.extend("Articles");
var article = new Articles();
Parse.Cloud.job("ArticleFeed", function(request, response) {
Parse.Cloud.httpRequest({
method: 'GET',
url: 'URL HERE',
success: function(httpResponse) {
var data= JSON.parse(httpResponse.text);
for (var i = 0; i < data[i].body.und.length; i++) {
article = new Articles(),
content = data[i];
article.set("body", content.body.und[0].value);
article.set("vid", content.vid);
article.set("title", content.title);
var epochTime = content.created;
var newDate = moment.utc(1234567890000);
article.set("date_created", newDate);
articles.push(article);
}
article.save();
response.success(httpResponse.text); // This will respond with the contents of the http response
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error('Request failed with response code ' + httpResponse.status);
}
});
});
编辑:这是正确的代码摘录,替换了上面不正确的 for 循环:
for (var i = 0; i < data[i].body.und.length; i++) {
article = new Articles(),
content = data[i];
article.set("body", content.body.und[0].value);
article.set("vid", content.vid);
article.set("title", content.title);
articles.push(article);
}
【问题讨论】:
-
您的代码在这一行出错:for (var i = 0; i jsonData 而不是
data? -
好电话,已解决。错误保持不变。
标签: javascript arrays json parsing parse-platform