关于javascript:Json解码和解析错误node.js

Json Decode and Parse Error node.js

本问题已经有最佳答案,请猛点这里访问。

嗨,我正在尝试这样做

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const request = require('request');
const zlib = require('zlib');
const opts = {
    uri: 'http://data.githubarchive.org/2015-01-01-15.json.gz',
    encoding: null,
};

request.get(opts, function(error, response, body) {
    if (!error) {
        zlib.gunzip(body, function(err, decoded) {
            if (err) {
                console.log(err)
            } else {
                var json_string = decoded.toString('utf-8').replace(/(\
\
|\
|\
)/gm,"").trim();
                var json = JSON.parse(json_string);
                console.log("SJON", typeof json)
            }
        });
    }
});

我正在执行以下步骤:

  • 从网址获取数据
  • 使用zlib.gunzip解压缩
  • 将该解码数据转换为字符串
  • 替换所有换行符和喙语句
  • 我正在尝试解析抛出错误的字符串
  • 使用JSON.parse解析数据时出现错误,这是github的公共dataset。我不知道我要去哪里错,任何人都可以帮忙。


    该文件每行包含一个JSON对象。仅删除换行符不会产生有效的单个JSON对象。相反,您可以在换行符上拆分输入数据,然后分别解析每行:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    zlib.gunzip(body, function(err, decoded) {
      if (err) {
        console.log(err);
      } else {
        let array = decoded.toString().trim().split(/\
    ?\
    /).map(line => JSON.parse(line));
        ...
      }
    });