将空值替换为JSON OBJECT中的空值

Ant*_*ony 11 javascript jquery json

嗨,我有一个由ajax请求提供的JSON对象.

json中的一些值显示为null,但我想empty String改为

我的代码示例:

$.post("/profil_process/wall/preview-post.php",param, function (data){
    // this does not work
    JSON.stringify(data, function(key, value) { return value === "" ? "" : value });
    $('#previewWall').html(getPostWall(data.type,data.titre,data.url,data.description,data.media,data.photo_auteur,data.nom_auteur,data.url_auteur,data.date_publication)).fadeIn();
    $(".bouton-vertM").show();
    $("#wLoader").hide();
},'json');
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Ami*_*leb 22

你的功能应该是这样的:

function (key, value) {
    return (value == null) ? "" : value
}
Run Code Online (Sandbox Code Playgroud)

检查nullundefined值并返回一个空字符串

  • 这可以重构为`返回值|| ""`; (3认同)

gra*_*vic 10

如果可以在序列化字符串上用空字符串替换null-s,请执行以下操作:

data = JSON.parse(JSON.stringify(data).replace(/\:null/gi, "\:\"\"")); 
Run Code Online (Sandbox Code Playgroud)


ade*_*neo 7

这是你应该如何做,用空字符串替换对象值,而不是字符串化

$.post("/profil_process/wall/preview-post.php",param, function (data){

    (function removeNull(o) {
        for(var key in o) {
            if( null === o[key] ) o[key] = '';
            if ( typeof o[key] === 'object' ) removeNull(o[key]);
        }
     })(data);

     $('#previewWall').html(
          getPostWall(
              data.type,
              data.titre,data.url,
              data.description,
              data.media,
              data.photo_auteur,
              data.nom_auteur,
              data.url_auteur,
              data.date_publication
          )  // ^^^ why not just pass the entire object ?
    ).fadeIn();

    $(".bouton-vertM").show();
    $("#wLoader").hide();

},'json');
Run Code Online (Sandbox Code Playgroud)