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) } }); } }); |
我正在执行以下步骤:
使用
该文件每行包含一个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)); ... } }); |