[英]JSON object but can't parse
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. 我需要在一个基于json的iTunes网址上查找引发json的内容,我正在使用nodejs的请求模块来获取json,它的确也返回了json,但是当我尝试解析它时不会返回我内部对象,但是像stringify或JSON.parse这样的调用都可以正常工作。 sample url https://itunes.apple.com/lookup?id=477091027 样本网址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 我现在机智了
you just need to add the parameter json:true
您只需要添加参数json:true
request({url:itunesUrl, json:true}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body.results[0].trackName)
}
});
Actually, you are stringify
ing the json before parse
-ing it again : 实际上,您是在parse
json之前对其进行stringify
再次对其进行parse
:
var jsonbody = JSON.stringify(body.trim());
var obj = JSON.parse(jsonbody);
If body
is supposed to contain json, then you directly should do 如果body
应该包含json,那么您应该直接执行
var obj = JSON.parse(body);
Even though Ninetainedo's answer looks correct, the docs suggest that you can use json: true
as a parameter in the request options. 即使Ninetainedo的答案看起来正确,文档仍建议您可以在请求选项中使用json: true
作为参数。 This will automatically parse the json into a object, removing the need for the JSON.parse()
line. 这将自动将json解析为一个对象,而无需使用JSON.parse()
行。
See https://github.com/request/request#requestoptions-callback 参见https://github.com/request/request#requestoptions-callback
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.