Replace null values to empty values in a JSON OBJECT

前端 未结 8 1682
無奈伤痛
無奈伤痛 2020-12-31 06:54

Hi I\'ve got a JSON object provided by an ajax request.

Some of the values inside the json appears as null, but I want an empty String inst

相关标签:
8条回答
  • 2020-12-31 07:27

    Hope this help

    var List = [];
    
    
    $.post("/profil_process/wall/preview-post.php",param, function (data){
    
    jQuery.each(data, function (key, value) {
                    List.push({
                        ReportId : value.ReportId,
                        ReportType: CheckNullReturnBlank(value.ReportType),
                        ReportName: CheckNullReturnBlank(value.ReportName),
                        Description : CheckNullReturnBlank(value.Description)
                    })
                });   },'json');
    
    
    
    function CheckNullReturnBlank(item) {
        return item = (item == null) ? '' : item;
    }
    
    0 讨论(0)
  • 2020-12-31 07:29

    Here's how you should be doing it, replacing the objects values with empty strings, not stringifying it

    $.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');
    
    0 讨论(0)
  • 2020-12-31 07:30

    If you can replace null-s with empty strings on serialized string, do something like this:

    data = JSON.parse(JSON.stringify(data).replace(/\:null/gi, "\:\"\"")); 
    
    0 讨论(0)
  • 2020-12-31 07:30
    function returnblank(item){
      if(item == null){
        return "";
      }else{
        return item;
      }
    }
    
    0 讨论(0)
  • 2020-12-31 07:38

    Your function should be like this:

    function (key, value) {
        return (value == null) ? "" : value
    }
    

    Checks null and undefined values and returns an empty string

    0 讨论(0)
  • 2020-12-31 07:41

    I recommend you the check the return type of the Ajax because it determines how to remove null.

    If it is string, you can use this:

    data = data.replace(/null/g, '""');  //Stays as string
    

    Or:

    data = JSON.parse(data);    // Turns to a JSON object
    

    If it is json object, then you can use this:

    data = JSON.stringify(data).replace(/null/g, '""');  //Turns to string
    
    0 讨论(0)
提交回复
热议问题