【问题标题】:Making HTTP request and parsing the result as JSON发出 HTTP 请求并将结果解析为 JSON
【发布时间】:2017-11-28 20:35:21
【问题描述】:

我想下载一个 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'

【问题讨论】:

  • 您的代码看起来正确。如果你 console.log(body)console.log("Fin"),你会得到什么
  • @samanime 我得到一个字符串,里面有一些看起来像 json 的东西。这是一个巨大的文件,我会用第一个字符更新问题。
  • 我问是因为你的代码应该没问题。将 JSON 字符串放入 JSON.parse(body) 应该可以正常工作。如果不是,则 JSON 中的某处可能存在语法错误。您可以针对在线解析器运行它并查看它的内容。
  • @samanime 是的,我通过 jsonlint 运行它。至少我通过firefox下载json后得到了什么。
  • 啊,是的,这确实有道理。看起来 JSON 有非 ASCII 字符,所以当它到达它们时,它可能会感到困惑。通常headers进来的时候应该指定它是UTF-8,但是貌似headers没有指定,所以你必须自己提供。

标签: javascript json node.js http request


【解决方案1】:

指定编码后测试和工作:

{encoding:'utf8'}

您请求的特定 url 似乎没有明确它在响应标头中的编码,所以我们必须像这样手动设置它:

 request(u ,{encoding:'utf8'}, 
   function(error, response, body) { console.log("Fin");  JSON.parse(body)  })

【讨论】:

  • @artium,仍在检查编码问题的原因
【解决方案2】:

试试这个:

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 文件的格式)

我尝试了代码,它可以工作。

בהצלחה!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 2021-12-17
    • 2018-11-09
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多