5

我正在尝试 json.stringify 一个 1 gb 的对象,以便我可以将其写入磁盘。我明白了FATAL ERROR: JS Allocation failed - process out of memory

我该怎么做才能成功地进行字符串化?

4

2 回答 2

5

您可以手动逐位字符串化:如果y是 的键,则为xJSON.stringify(y) + ":" + JSON.stringify(x[y])提供一个段。

使用fs.appendFileSync,例如,您可以使用:

var output = "out.json";
fs.writeFileSync(output, "{");
var first = true;
for(var y in x) {
    if(x.hasOwnProperty(y)) {
        if(first) first = false;
        else fs.appendFileSync(output, ",");
        fs.appendFileSync(output, JSON.stringify(y) + ":" + JSON.stringify(x[y]))
    }
} 
fs.appendFileSync(output, "}");

您还可以使用写入流

于 2013-07-21T04:51:42.740 回答
0

扩展对象,数组检查器

var first, y, i$, ref$, len$, toString$ = {}.toString;
switch (toString$.call(x).slice(8, -1)) {
case 'Object':
  fs.writeFileSync(output, '{');
  first = true;
  for (y in x) {
    if (x.hasOwnProperty(y)) {
      if (first) {
        first = false;
      } else {
        fs.appendFileSync(output, ',');
      }
      fs.appendFileSync(output, JSON.stringify(y) + ':' + JSON.stringify(x[y]));
    }
  }
  fs.appendFileSync(output, '}');
  break;
case 'Array':
  fs.writeFileSync(output, '[');
  first = true;
  for (i$ = 0, len$ = (ref$ = x).length; i$ < len$; ++i$) {
    y = ref$[i$];
    if (first) {
      first = false;
    } else {
      fs.appendFileSync(output, ',');
    }
    fs.appendFileSync(output, JSON.stringify(y));
  }
  fs.appendFileSync(output, ']');
  break;
default:
  fs.writeFileSync(output, JSON.stringify(x));
}
于 2016-03-18T09:38:59.710 回答