我想下载一个JSON并解析它。我尝试了以下方法:
var request = require('request');
var url = "http://iiif.nli.org.il/collections/danhadani.json"
var result = request(url , function(error, response, body) {
console.log("Fin");
JSON.parse(body);
});
undefined
> Fin
Fin
SyntaxError: Unexpected token
at Object.parse (native)
at Request._callback (repl:1:81)
at Request.self.callback (/home/artium/Projects/nlihack-team-m7/node_modules/request/request.js:186:22)
at emitTwo (events.js:87:13)
at Request.emit (events.js:172:7)
at Request.<anonymous> (/home/artium/Projects/nlihack-team-m7/node_modules/request/request.js:1163:10)
at emitOne (events.js:77:13)
at Request.emit (events.js:169:7)
at IncomingMessage.<anonymous> (/home/artium/Projects/nlihack-team-m7/node_modules/request/request.js:1085:12)
at IncomingMessage.g (events.js:260:16)
我能够记录正文中检索到的JSON字符串,对我来说看起来不错,所以我猜我的解析错误了。
编辑:
身体的第一个字符看起来像这样:
> body.substring(1,250)
'{"@context":"http://iiif.io/api/presentation/2/context.json",\n"@id": "http://iiif.nli.org.il/collections/danhadani.json",\n"@type":"sc:Collection",\n"label":"Dan Hadani Collection", \n"attribution":[{"@value":"The National Library of Israel","@language'
答案 0 :(得分:1)
试试这个:
var request = require('request');
var url = "http://iiif.nli.org.il/collections/danhadani.json";
var options = {
uri: url,
method: 'GET',
json : true,
encoding: 'utf8'
};
var r = request(options , function(error, response, body) {
console.log("Fin");
// now you have an Array(43515) of objects on body.members without the need of parsing.
console.log(`The first object in the json file is: ${body.members[0]}`);
});
您将获取数据作为对象数组(因为该json文件的格式)
我尝试了代码,但它确实有效。
בהצלחה!