保留未定义的JSON.stringify否则将删除 [英] Preserving undefined that JSON.stringify otherwise removes

查看:99
本文介绍了保留未定义的JSON.stringify否则将删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

以下是一个示例:

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

var string = JSON.stringify(hash);

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

电子邮件消失来自JSON.stringify。

Email disappeared from JSON.stringify.

推荐答案

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

You can pass a replacer function to JSON.stringify to automatically convert undefined values to null values, like this:

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

这适用于数组内的未定义值,如 JSON.stringify 已将这些转换为 null

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

这篇关于保留未定义的JSON.stringify否则将删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆