Reputation: 5113
I need to do a lookup onto an itunes url which throws the json, in my nodejs based backend, i am using requests module of nodejs to get the json, and it indeed returns me the json as well, but the moment i try parsing it doesn't return me internal objects, however calls like stringify or JSON.parse just work without any exception. sample url https://itunes.apple.com/lookup?id=477091027
//sample url https://itunes.apple.com/lookup?id=477091027
request(itunesUrl, function (error, response, body) {
if (!error && response.statusCode == 200) {
var jsonbody = JSON.stringify(body.trim());
var obj = JSON.parse(jsonbody);
console.log(obj);
/*for(var myKey in obj)
{
console.log("key:"+myKey+", value:"+obj[myKey]);
}*/
//none of these show value in them
appinfo.appname = obj.results[0].trackName;
appinfo.appImage = obj.results[0].artworkUrl60;
appinfo.appCategory = obj.results[0].genres[0];
}
});
I am at my wits end now
Upvotes: 0
Views: 2239
Reputation: 88
you just need to add the parameter json:true
request({url:itunesUrl, json:true}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body.results[0].trackName)
}
});
Upvotes: 1
Reputation: 2495
Even though Ninetainedo's answer looks correct, the docs suggest that you can use json: true
as a parameter in the request options. This will automatically parse the json into a object, removing the need for the JSON.parse()
line.
See https://github.com/request/request#requestoptions-callback
Upvotes: 0
Reputation: 3389
Actually, you are stringify
ing the json before parse
-ing it again :
var jsonbody = JSON.stringify(body.trim());
var obj = JSON.parse(jsonbody);
If body
is supposed to contain json, then you directly should do
var obj = JSON.parse(body);
Upvotes: 1