语法错误:意外的令牌 JSON:解析错误



所以,错误是如此明显,以至于我得到了很多相同的结果,但是我发现的任何修复程序似乎都没有正常工作。我只是在调用一个 JSON API,它只会导致"字符串"响应。

但是,当我通过 JSON.parse 传递它时,它会抛出意外令牌错误。下面是示例 API 代码,

{
  states: [
    {
      name: "Gujarat",
      cities: [ ]
    },
    {
      name: "Haryana",
      cities: [
         {
          name: "Faridabad",
          url: "faridabad",
          popular: false
         },
         {
          name: "Gurgaon",
          url: "gurgaon",
          popular: false
         }
      ]
   }
  ]
}

这是我正在尝试执行的咖啡脚本代码,

request = require 'request'
url = "http://example.com/example.v1.json"
request url: url, json: true, (error, response, body) ->
  if !error && response.statusCode == 200
    jsonObject = JSON.parse body
    console.log typeof(body)

和 JS 版本

// Generated by CoffeeScript 1.8.0
(function() {
  var request, url;
  request = require('request');
  url = "http://example.com/example.v1.json";
  request({
    url: url,
    json: true
  }, function(error, response, body) {
    var jsonObject;
    if (!error && response.statusCode === 200) {
      jsonObject = JSON.parse(body);
      return console.log(typeof body);
    }
  });
}).call(this);

我得到的错误是,

SyntaxError: Unexpected token 
    at Object.parse (native)
    at Request._callback (/Users/avinoth/learnrepo/Reponame/newtest.js:15:25)
    at Request.self.callback (/Users/avinoth/learnrepo/Reponame/node_modules/request/request.js:121:22)
    at Request.emit (events.js:98:17)
    at Request.<anonymous> (/Users/avinoth/learnrepo/Reponame/node_modules/request/request.js:978:14)
    at Request.emit (events.js:117:20)
    at IncomingMessage.<anonymous> (/Users/avinoth/learnrepo/Reponame/node_modules/request/request.js:929:12)
    at IncomingMessage.emit (events.js:117:20)
    at _stream_readable.js:943:16
    at process._tickCallback (node.js:419:13)

传递的数据仅为字符串类型。

不仅对于这个 api,我什至尝试了不同的 api,例如 https://osrc.dfm.io/avinoth.json

使用此链接成功解析 JSON,没有任何错误,http://json.parser.online.fr/

请帮帮我..

{ 'content-type': 'text/html; charset=UTF-8',
  'content-length': '1436',
  connection: 'keep-alive',
  date: 'Mon, 08 Dec 2014 10:27:34 GMT',
  'cache-control': 'public, max-age=5, s-maxage=5',
  'content-encoding': 'gzip',
  'last-modified': 'Mon, 08 Dec 2014 10:26:36 GMT',
  etag: '"ed710ee54481a6d6e30da823bd19a511"',
  'accept-ranges': 'bytes',
  server: 'AmazonS3',
  'x-cache': 'RefreshHit from cloudfront',
  via: '1.1 05b6ee20d35c57dfb14b821a9c7edd15.cloudfront.net (CloudFront)',
  'x-amz-cf-id': 'ZuUcdEqp-ip1GY51NX9A8x-5lwBpaEo9uX1gQK7N5gWn_mMmAvo3og==' }

刚才我注意到,响应正文只是一团无法识别的字符......

'u001f�bu0000�|�Tu0000u0003��Qo�6fǿJ��u0006}���6l���b+6`�=бf+�dC�\$E���8�(5�u001eu0002��g[2ER|�Mu001e��v����,u0018�{�}g���ݳ�ZM��~w�^u0017�u0018�afu000efu000eu0007ףu0004Tu001a�1��v��B?��{ro�`��Wt�u0012u000b~j��u0019�u0013+*��PU�׉�6�|n��u000eu001a�u0012v�4u0001�=N�u000fN��u0013���u001bX��u000fS��Tu0014a�f��`"n�Pu0017+|�u0012u000b���n�QW���G8�W\�H4I��a��D\-���S��NDu0012D(�f��u0002���+K�(��O��a$�i��B?�m���>5�:������u0017贅:�l�u0004u0001�tu0015��RIᱡ�.�m&u000fu0004g�!}�.�,�+t]��=�X�+u001cZ��W3Iu0010!�u001a#xKu001ehnU��*TPAMX"t��u0001Cu0006}ۤ��u0013^t"�o�- u000e&�r4n�\��t�S�$�P��6�xT���Ru000e����pֳRurKKu0014u0016��6u0003IV�f��3�u0019�Γ㘋u0002|�(��7ܽu0004��-��ޯC��0&u0014tz�u0012u000b�u000eGhM�\�­�4u0016�u0003�W���S.���u0018�p,��D%u0016|�����7�u0007�u000b�au0004I�b�4��$�П��u001f��u0006ݙJu0002hC7،K��MеPl��Pu0005���u0018k��:�bu0001�r����<��b��0Se�BE�x[�BV��rѰRE[(/jhHm�Z|:u000eU������b�3|=Mt"f3��Qn�u000bn�Ҹ3�Q��u0006Iu0010�h�Yu0011d ӄ����A�eO��v�,����2K�u0002"teu0001^u"o�%�_��I����u0014u0000f�u001e+�sK�f.n��u000e沐$�u0010I��'����Hu0014u001e�5�)u0014m>u0014�K�����-B��5���%��u0007��%��u000bu0018��=�%a��c\�,�u0003Q�c�³r=�l6���u0007m*�4�u001f��>��u0016�X�b5�u0004�Gu0007u0000}蔽{�Ye>���cu001c�o�5�oC�qi&u0015r���2��Rt&�I������]�t9�'Ǎ�jt�t��S ~Eu0014u0001S���WKL�8e�ƪ<���xu000b,u001agU�I�뇱�:�ͬ��u001e���5B��<����u0001$�Ou0002�fCzu000f�L�u0017�e2�|ѪLu0013�/����D�Lu0013:0��l�6S8�_�u000eu001a�u0016�u0016M��)u001d����SK%�u00168c$�_�%��]J���$u001e<ժxu001eQ����r�jSTy�P�VB]��Du0011��kr�<F[@����x!u0014��n�`t��b�^� �]:�H��6����$�����E�GZ�<Mu001cі�(�9��%5u000b�u000fI��!n�)���&t<��t�Gu0013�.3�&���&۝6t<���r��u0014�3zu0000�\�(Bu001d��5K�y�������:RI��f��ԛu001c���\��ꙒS�t��7$$��3~u001bro��ă�u0010lu0019��\�a�߸/�՝r��5u0006�l���Cu0001]9���Wu0006`kZu0017l�p�^::tEf���_x�rv��ku0012X�ohU��g*}(]����a����V����y���l�!u001b�.o�U���u0015���b��u0018�x��w�z��眬ϱ�q���~��B�n=<��u000f�u00051E�GФ]�>u0014��pn5�qu0015�u0012u0015u001c5���U�+��u0011�u0016�#��u000f�u0005�D�8̼�N�j̱�zm�F(5YcQu001f)Z�o�z2��1���?�u001f'Tpu001cu0000u0000' 

终于,我找到了。内容是由头文件中提到的"gzip"压缩的,直到这个时候我才注意到这一点。由于压缩,服务器正在发送JSON.parse无法理解的乱码文本,并抛出了意外令牌错误。

我在节点中使用 zlib 库解压缩.js...

下面是代码,我用来解压缩它,

requestWithEncoding = (url, callback) ->
  req = request.get url
  req.on 'response', (res) ->
    chunks = []
    res.on 'data', (chunk) ->
      chunks.push chunk
    res.on 'end', ->
      buffer = Buffer.concat chunks
      encoding = res.headers['content-encoding']
      if encoding == 'gzip'
        zlib.gunzip buffer, (err, decoded) ->
          callback err, decoded && decoded.toString()
      else
        callback null, buffer.toString()
  req.on 'error', (err) ->
    callback err

看起来 api 服务器的响应不是您的request模块可以处理的。也许将响应标头设置为 application/json ?或者在客户端,请求 json?

最新更新