我正在使用node.js yahoo-finance模块来检索Apple和Google股票价格。这有效,代码如下所示。
var util = require('util');
require('colors');
var _ = require('lodash');
var yahooFinance = require('yahoo-finance');
var FIELDS = _.flatten([
//symbol,name, lastTradeDate, lastTradePriceOnly,
['s', 'n', 'd1', 'l1']
]);
var SYMBOLS = [
'AAPL',
'GOOG',
];
yahooFinance.snapshot({
fields: FIELDS,
symbols: SYMBOLS
}).then(function (result) {
_.each(result, function (snapshot, symbol) {
console.log(JSON.stringify(snapshot, null, 2));
});
});
最后console.log(JSON.stringify(snapshot, null, 2));
的输出如下所示;
{
"symbol": "AAPL",
"name": "Apple Inc.",
"lastTradeDate": "2015-11-03T16:00:00.000Z",
"lastTradePriceOnly": 122
}
{
"symbol": "GOOG",
"name": "Alphabet Inc.",
"lastTradeDate": "2015-11-03T16:00:00.000Z",
"lastTradePriceOnly": 728.11
}
问题是它看起来像json但它仍然不是格式正确的json。
所需的json看起来像这样;
[{
"symbol": "AAPL",
"name": "Apple Inc.",
"lastTradeDate": "2015-11-03T16:00:00.000Z",
"lastTradePriceOnly": 122
},
{
"symbol": "GOOG",
"name": "Alphabet Inc.",
"lastTradeDate": "2015-11-03T16:00:00.000Z",
"lastTradePriceOnly": 728.11
}]
如何更改代码以获得所需的json输出?这很棘手,因为每个json对象都是按任务而不是一次性异步释放的。
答案 0 :(得分:0)
感谢ojovirtua的评论,我找到了答案。
yahooFinance.snapshot({
fields: FIELDS,
symbols: SYMBOLS
}).then(function (result) {
console.log(JSON.stringify(result));
});