【问题标题】:Update values in multiple large JSON files更新多个大型 JSON 文件中的值
【发布时间】:2017-09-05 10:20:22
【问题描述】:
我有一个包含多个大型 JSON 文件的文件夹,并且想要优化它们。我使用gulp 和gulp-replace 来删除空格。
这些文件包含一个大型 JSON 对象,我想在某些子属性下更新一些值。由于文件很大,我正在研究 JSON 流以保持较低的内存占用。有几个 JSON 流媒体库,如 JSONStream、BFJ、Oboe 和 stream-json。
JSONStream 似乎是最容易使用的一种,因为它允许使用占位符进行路径匹配,但匹配的值似乎仅用于提取数据而不用于更新。
所以我想要实现的是流式传输数据,解析一些特定的子对象,更新它的值,再次将该子对象字符串化,然后将带有更新值的整个数据保存回磁盘。
【问题讨论】:
标签:
json
node.js
stream
gulp
【解决方案1】:
我设法使用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
;