使用以下网址。
http://d.yimg.com/aq/autoc?region=US&lang=en-US&query=google
我得到以下内容......
{
"ResultSet":{
"Query":"Google",
"Result":[
{
"symbol":"GOOG34F.SA",
"name":"GOOGLE DRN A",
"exch":"SAO",
"type":"S",
"exchDisp":"Sao Paolo",
"typeDisp":"Equity"
},
{
"symbol":"^VXGOG",
"name":"CBOE EQUITY VIXON GOOGLE",
"exch":"WCB",
"type":"I",
"exchDisp":"Chicago Board Options Exchange",
"typeDisp":"Index"
},
{
"symbol":"GOOG34.SA",
"name":"GOOGLE DRN A",
"exch":"SAO",
"type":"S",
"exchDisp":"Sao Paolo",
"typeDisp":"Equity"
},
{
"symbol":"GOOG35.SA",
"name":"GOOGLE DRN C",
"exch":"SAO",
"type":"S",
"exchDisp":"Sao Paolo",
"typeDisp":"Equity"
},
{
"symbol":"GOOG35F.SA",
"name":"GOOGLE DRN C",
"exch":"SAO",
"type":"S",
"exchDisp":"Sao Paolo",
"typeDisp":"Equity"
}
]
}
}
如何遍历它以获取每个符号和名称?我在服务器上使用node.js.试过......
var request = require('request');
var _ = require('lodash');
var url = "http://d.yimg.com/aq/autoc?region=US&lang=en-US&query=google";
request(url, function (error, response, data) {
if (!error && response.statusCode == 200) {
var textToOuput = 'Results\n\n';
_.each(data.ResultSet.Result, function(i, Result){
textToOutput += "Symbol: "+Result.symbol+", Name: "+Result.name+"\n");
});
}
});
但是得到以下错误:
_.each(data.ResultSet.Result, function(i, Result){
^
TypeError: Cannot read property 'Result' of undefined
答案 0 :(得分:1)
您可以使用forEach循环浏览数据
var _getResult = _myObject.ResultSet.Result;
_getResult.forEach(function(item){
document.write('<pre> Symbol --'+item.symbol+' Name --'+item.name+'</pre>')
})
答案 1 :(得分:0)
这是因为数据类型是字符串,而不是对象。您可以先使用JSON.parse(data)
将其转换为对象。
答案 2 :(得分:0)
这是完整的工作代码,只需将其保存在任何节点应用程序,安装请求和lodash软件包(npm install),它将按预期打印您的名称和符号。
Below corrections added in your code -
1) You need to parse string into json (JSON.parse(data)
2) textToOutput was undefined, corrected variable name.
3) in look call back function, 1st arguments is current item or object of running iterator , and 2nd param is index.
最终输出(根据当前结果) -
Results
Symbol: GOOG34F.SA, Name: GOOGLE DRN A
Symbol: ^VXGOG, Name: CBOE EQUITY VIXON GOOGLE
Symbol: GOOG34.SA, Name: GOOGLE DRN A
Symbol: GOOG35.SA, Name: GOOGLE DRN C
Symbol: GOOG35F.SA, Name: GOOGLE DRN C
工作代码:
var request = require('request');
var _ = require('lodash');
var url = "http://d.yimg.com/aq/autoc?region=US&lang=en-US&query=google";
request(url, function (error, response, data) {
if (!error && response.statusCode == 200 && null !== data) {
var resultJsonData = JSON.parse(data);
var textToOutput = 'Results\n\n';
_.each(resultJsonData.ResultSet.Result, function (curItem, i) {
textToOutput += "Symbol: " + curItem.symbol + ", Name: " + curItem.name + "\n";
});
console.log(textToOutput);
}
});