我已经在一个应用程序上工作了一段时间,这个特定的功能是一个函数的一部分,该函数应该将数据从 api 读取到数组中,以便我可以在网页上显示内容。现在,我被困在这里了。最初,我有一段较长的代码无法正常工作,但我已将其简化为一个更具体的问题: jsonBody.length 按预期返回 5,但articles.length 返回“未定义”,我不明白为什么。
request(options, function(err, request, body) {
var jsonBody = JSON.parse(body);
var articles = new Article(jsonBody);
console.log(jsonBody.length);
console.log(articles.length);
res.render('news');
});
如果您能帮助我理解,非常感谢。我什至不完全确定我应该使用 var 文章吗?我可以将 JSON 打印到控制台,只需查找是否使用 jsonBody,但如果这样做,我不确定如何利用“新闻”页面上的内容。
这里是扩展代码,以防您想查看。
var marketNewsSchema = new mongoose.Schema({
datetime: String,
headline: String,
source: String,
url: String,
summary: String,
related: String,
Image: String
});
var Article = mongoose.model('MarketNews', marketNewsSchema);
app.get('/api/marketNews', function(req, res) {
var query = {
'symbol': req.body.id
};
var options = {
url: 'https://api.iextrading.com/1.0/stock/aapl/news/last/5',
method: 'GET',
qs: query
};
request(options, function(err, request, body) {
var jsonBody = JSON.parse(body);
var articles = new Article(jsonBody);
console.log(jsonBody.length);
console.log(articles.length);
res.render('news');
});
});
原始 JSON 对象应采用以下格式:
[
{
"datetime": "2017-06-29T13:14:22-04:00",
"headline": "Voice Search Technology Creates A New Paradigm For Marketers",
"source": "Benzinga via QuoteMedia",
"url": "https://api.iextrading.com/1.0/stock/aapl/article/8348646549980454",
"summary": "<p>Voice search is likely to grow by leap and bounds, with technological advancements leading to better adoption and fueling the growth cycle, according to Lindsay Boyajian, <a href=\"http://loupventures.com/how-the-future-of-voice-search-affects-marketers-today/\">a guest contributor at Loup Ventu...",
"related": "AAPL,AMZN,GOOG,GOOGL,MSFT",
"image": "https://api.iextrading.com/1.0/stock/aapl/news-image/7594023985414148"
}
]
最佳答案
我认为你的问题是 new Article()
不是一个数组,但你希望它是一个数组。
据我所知,Article
是一个 Mongoose 模式 - 而不是一个数组。
因此,如果您的 jsonBody
是一个文章数组,您可能需要映射该数组并为列表中的每个对象生成单独的文章。
即:
var jsonBody = JSON.parse(body);
var articles = jsonBody.map(function(data) {
return new Article(data);
})
console.log(articles.length);
关于javascript - 将解析后的 JSON 读入数组不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53554596/