MorningSleeper MorningSleeper - 5 months ago 10
JSON Question

How to loop through this?

Using the URL below.

http://d.yimg.com/aq/autoc?region=US&lang=en-US&query=google

I am getting the following ...

{
"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"
}
]
}
}


How do I loop through it to get the symbol and name of each? I am using node.js on server. Tried following ...

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");
});

}

});


But get following error:

_.each(data.ResultSet.Result, function(i, Result){
^
TypeError: Cannot read property 'Result' of undefined

Answer

it's because the type of data is string, not a object. you can use JSON.parse(data) to convert it to an object first.