用JSON中的引号替换null

GoB*_*avs 2 javascript json

本主题针对PHP和Rails在本网站上进行了讨论,但我没有看到标准JavaScript的任何内容.

如果我的JSON对象在一对中具有空值,则它看起来像这个id:null但我需要它看起来像这个id:""

由于JSON不支持单引号,我不确定如何执行此操作.

目前的结果

{"id":"e6168d55-1974-e411-80e0-005056971214","label":"List","parentId":null}
Run Code Online (Sandbox Code Playgroud)

期望的结果

{"id":"e6168d55-1974-e411-80e0-005056971214","label":"List","parentId":""}
Run Code Online (Sandbox Code Playgroud)

aps*_*ers 7

JSON.stringify接受允许您用其他值替换值的替换器回调.对于在输入中处理的每个键值对,都会运行replacer回调,并将其替换为返回值.

只需让你的replacer回调查找任何null值,并用空字符串替换它们:

var myObj = {
               "id":"e6168d55-1974-e411-80e0-005056971214",
               "label":"List",
               "parentId":null
             };

JSON.stringify(myObj, function(key, value) {
    // if value is null, return "" as a replacement
    if(value === null) {
        return "";
    }

    // otherwise, leave the value unchanged
    return value;
});
Run Code Online (Sandbox Code Playgroud)

如果您没有对象,但只有JSON作为输入,则可以使用构建对象 var myObj = JSON.parse(jsonInput);