在执行JSON.stringify(hash)时如何保留未定义的值?
这是一个例子:
var hash = {
"name" : "boda",
"email" : undefined,
"country" : "africa"
};
var string = JSON.stringify(hash);
> "{"name":"boda","country":"africa"}"
Run Code Online (Sandbox Code Playgroud)
电子邮件从JSON.stringify中消失了.
Fli*_*imm 91
您可以传递一个替换器函数来JSON.stringify自动将undefined值转换为null值,如下所示:
var string = JSON.stringify(
obj,
function(k, v) { return v === undefined ? null : v; }
);
Run Code Online (Sandbox Code Playgroud)
这适用于数组内部的未定义值,因为JSON.stringify已经将它们转换为null.
您可以通过转换为来保留密钥,null因为有效的 JSON 不允许undefined;
简单的一个班轮:
JSON.stringify(obj, (k, v) => v === undefined ? null : v)
Run Code Online (Sandbox Code Playgroud)
用null而不是undefined.
var hash = {
"name" : "boda",
"email" : null,
"country" : "africa"
};
var string = JSON.stringify(hash);
> "{"name":"boda","email":null,"country":"africa"}"
Run Code Online (Sandbox Code Playgroud)
function stringifyWithUndefined(value: any, space: number): string {
const str = JSON.stringify(
value,
(_k, v) => v === undefined ? '__UNDEFINED__' : v,
space
);
return str.replaceAll('"__UNDEFINED__"', 'undefined');
}
Run Code Online (Sandbox Code Playgroud)
示例1:
const object = {
name: 'boda',
email: undefined,
country: 'africa'
};
console.log(stringifyWithUndefined(object, 2));
Run Code Online (Sandbox Code Playgroud)
结果(字符串):
{
"name": "boda",
"email": undefined,
"country": "africa"
}
Run Code Online (Sandbox Code Playgroud)
示例2:
const array = [object, { object }, [[object]]];
console.log(stringifyWithUndefined(array, 2));
Run Code Online (Sandbox Code Playgroud)
结果(字符串):
[
{
"name": "boda",
"email": undefined,
"country": "africa"
},
{
"object": {
"name": "boda",
"email": undefined,
"country": "africa"
}
},
[
[
{
"name": "boda",
"email": undefined,
"country": "africa"
}
]
]
]
Run Code Online (Sandbox Code Playgroud)
请注意,这undefined不是有效的 JSON,如果您给出以下结果,JSON.parse()则会失败SyntaxError: Unexpected token [...] is not valid JSONstringifyWithUndefined()
这应该可以解决问题
// 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')
Run Code Online (Sandbox Code Playgroud)