Javascript 保留未定义的 JSON.stringify 否则会删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26540706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:01:04  来源:igfitidea点击:

Preserving undefined that JSON.stringify otherwise removes

javascriptjson

提问by bodacydo

How do I preserve undefined values when doing JSON.stringify(hash)?

执行 JSON.stringify(hash) 时如何保留未定义的值?

Here's an example:

下面是一个例子:

var hash = {
  "name" : "boda",
  "email" : undefined,
  "country" : "africa"
};

var string = JSON.stringify(hash);

> "{"name":"boda","country":"africa"}"

Email disappeared from JSON.stringify.

电子邮件从 JSON.stringify 中消失了。

回答by Flimm

You can pass a replacer function to JSON.stringifyto automatically convert undefinedvalues to nullvalues, like this:

您可以传递一个替换函数来JSON.stringify自动将undefined值转换为null值,如下所示:

var string = JSON.stringify(
  obj,
  function(k, v) { return v === undefined ? null : v; }
);

This works for undefined values inside arrays as well, as JSON.stringifyalready converts those to null.

这也适用于数组中的未定义值,因为JSON.stringify已经将它们转换为null.

回答by Efog

Use nullinstead of undefined.

使用null代替undefined

var hash = {
  "name" : "boda",
  "email" : null,
  "country" : "africa"
};

var string = JSON.stringify(hash);

> "{"name":"boda","email":null,"country":"africa"}"

回答by chickens

You can preserve the key by converting to nullsince a valid JSON does not allow undefined;

您可以通过转换为来保留密钥,null因为有效的 JSON 不允许undefined

Simple one liner:

简单的一个班轮:

JSON.stringify(obj, (k, v) => v === undefined ? null : v)

回答by Zizaco

This should do the trick

这应该可以解决问题

// Since 'JSON.stringify' hides 'undefined', the code bellow is necessary in
// order to display the real param that have invoked the error.
JSON.stringify(hash, (k, v) => (v === undefined) ? '__undefined' : v)
    .replace('"__undefined"', 'undefined')

回答by Peter

Im reading between the lines here and guessing that you want to have the value undefined when you use JSON.parse?

我正在阅读此处的内容并猜测您希望在使用 JSON.parse 时未定义值?

If that is the case you could use the following:

如果是这种情况,您可以使用以下方法:

var encodeUndefined = function(obj, undefinedPaths, path) {
  path = path || 'ROOT';
  for (var key in obj) {
    var keyPath = path + '.' + key;
    var value = obj[key];
    if (value === undefined) {
      undefinedPaths.push(keyPath);
    } else if (typeof value == "object" && value !== null) {
      encodeUndefined(obj[key], undefinedPaths, keyPath);
    }
  }
}

var stringifyAndPreserveUndefined = function(obj) {
  var undefinedPaths = [];
  //save all paths that have are undefined in a array.
  encodeUndefined((obj), undefinedPaths);
  return JSON.stringify({
    ROOT: obj,
    undefinedPaths: undefinedPaths
  }, function(k, v) { if (v === undefined) { return null; } return v; });
}

var parseAndRestoreUndefined = function(value) {
  var data = JSON.parse(value);
  var undefinedPaths = data.undefinedPaths;
  var obj = data.ROOT;
  //Restore all undefined values
  for (var pathIndex = 0; pathIndex < undefinedPaths.length; pathIndex++) {
    var pathParts = undefinedPaths[pathIndex].substring(5).split('.');
    var item = obj;
    for (var pathPartIndex = 0; pathPartIndex < pathParts.length - 1; pathPartIndex++) {
      item = item[pathParts[pathPartIndex]];
    }
    item[pathParts[pathParts.length - 1]] = undefined;
  }
  return obj;
}

var input = {
  test1: 'a',
  test2: 'b',
  test3: undefined,
  test4: {
    test1: 'a',
    test2: undefined
  }
};
var result = stringifyAndPreserveUndefined(input);
var result2 = parseAndRestoreUndefined(result);

stringifyAndPreserveUndefinedwill encode all undefined values in a array and when you call parseAndRestoreUndefinedit will put them in the correct place again.

stringifyAndPreserveUndefined将对数组中的所有未定义值进行编码,当您调用parseAndRestoreUndefined它时,它将再次将它们放在正确的位置。

The one downside is the json will not look exactly like the object. In the example above it will turn into {"ROOT":{"test1":"a","test2":"b","test4":{"test1":"a"}},"undefinedPaths":["ROOT.test3","ROOT.test4.test2"]}

一个缺点是 json 看起来与对象不完全一样。在上面的例子中,它将变成{"ROOT":{"test1":"a","test2":"b","test4":{"test1":"a"}},"undefinedPaths":["ROOT.test3","ROOT.test4.test2"]}

回答by tanguy_k

function stringifyWithUndefined(obj, space) {
  const str = JSON.stringify(obj, (key, value) => value === undefined ? '__undefined__' : value, space);
  return str.replace(/"__undefined__"/g, 'undefined');
}

Example:

例子:

const obj = {
  name: 'boda',
  email: undefined,
  country: 'africa'
};
console.log(stringifyWithUndefined(obj, 2));

Result:

结果:

{
  "name": "boda",
  "email": undefined,
  "country": "africa"
}

回答by Dustin Poissant

This will cause it to print as undefinedbut this is INVALID json, but is valid JavaScript.

这将导致它打印为undefined但这是无效的 json,但它是有效的 JavaScript。

var string = JSON.stringify(obj, function(k,v){return v===undefined?"::undefined::":v}, 2).replace(new RegExp("\"::undefined::\"", 'g'), "undefined");