我有一个包含几个大型JSON文件的文件夹,并希望对它们进行优化。我使用gulp和gulp-replace删除空白。
这些文件包含一个大型JSON对象,在某个子属性下,我想更新一些值。由于文件很大,所以我查看了JSON流,以保持较低的内存占用。有几个JSON流库,如JSONStream、BFJ、双簧管和流-json可用。
JSONStream似乎是最容易使用的,因为它允许与占位符匹配路径,但匹配的值似乎只用于提取数据,而不是用于更新。
所以我想要实现的是流数据,解析一些特定的子对象,更新它的值,再次压缩子对象,用更新的值保存整个数据到磁盘上。
发布于 2017-04-11 10:06:58
我用JSONStream设法让它正常工作。最近添加的功能是发出header和footer事件,以获得我感兴趣的匹配前后的日期。
var es = require('event-stream');
var JSONStream = require('JSONStream');
var isFirst = false;
var isHeader = false;
fs.createReadStream('filename.geojson')
.pipe(JSONStream.parse(['features', true], function(data) {
// map the data
return data;
}))
.on('header', function(data) {
// push the part before the first match
this.push(data);
})
.pipe(es.through(function write(data) {
if(isHeader === false) {
let dataStr = JSON.stringify(data);
// recreate the original structure
dataStr = dataStr.substring(0, dataStr.length - 1) +
',"features":[\n';
isHeader = true;
this.emit('data', dataStr);
} else {
// stringify the data and add a comma to each of the
// matched lines except the first one
let dataStr = (isFirst === true ? ',' : '') +
JSON.stringify(data) + '\n';
isFirst = true;
this.emit('data', dataStr);
}
}, function end() {
// properly close the json
this.emit('data', ']}');
this.emit('end');
}))
// store the json
;https://stackoverflow.com/questions/43322042
复制相似问题