2

我一直在尝试使用 JSONStream 读取文件,但我在这方面没有太多经验,而且很难找到有关它的信息(教程、文档)。

我在这里的某个地方找到了这段代码:

var fs = require('fs'),
    JSONStream = require('JSONStream');

var stream = fs.createReadStream('tst.json', {encoding: 'utf8'}),
    parser = JSONStream.parse();

stream.pipe(parser);

console.log(parser);

parser.on('root', function (obj) {
  console.log(obj); // whatever you will do with each JSON object
});

我试图将它与这样的 json 测试文件一起使用:

{
    "colors": [{
            "color": "black",
            "category": "hue",
            "type": "primary",
            "code": {
                "rgba": [255, 255, 255, 1],
                "hex": "#000"
            }
        },
        {
            "color": "white",
            "category": "value",
            "code": {
                "rgba": [0, 0, 0, 1],
                "hex": "#FFF"
            }
        },
        {
            "color": "red",
            "category": "hue",
            "type": "primary",
            "code": {
                "rgba": [255, 0, 0, 1],
                "hex": "#FF0"
            }
        },
        {
            "color": "blue",
            "category": "hue",
            "type": "primary",
            "code": {
                "rgba": [0, 0, 255, 1],
                "hex": "#00F"
            }
        },
        {
            "color": "yellow",
            "category": "hue",
            "type": "primary",
            "code": {
                "rgba": [255, 255, 0, 1],
                "hex": "#FF0"
            }
        },
        {
            "color": "green",
            "category": "hue",
            "type": "secondary",
            "code": {
                "rgba": [0, 255, 0, 1],
                "hex": "#0F0"
            }
        }
    ]
}

而且我认为它会返回所有对象但什么也没发生,它甚至没有进入“parser.on('root',function(obj)”。我该怎么做才能使这项工作?

4

1 回答 1

3

root事件已从 中删除JSONStream。改用data事件。https://github.com/dominictarr/JSONStream/commit/97d973ac59d0e58748cec98ea87aae36e057d368

还应指定 JSON 路径作为JSONStream.parse(). 对于您的 JSON,它可能是JSONStream.parse('colors.*')

所以把所有东西放在一起,它应该是

var fs = require('fs'),
    JSONStream = require('JSONStream');

var stream = fs.createReadStream('tst.json', {encoding: 'utf8'}),
    parser = JSONStream.parse('colors.*');

stream.pipe(parser);

parser.on('data', function (obj) {
  console.log(obj); // whatever you will do with each JSON object
});
于 2018-03-15T11:34:14.693 回答