Skip to content Skip to sidebar Skip to footer

Replace Null Values To Empty Values In A Json Object

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 instead My sample of code : $

Solution 1:

Your function should be like this:

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

If the value is null, then it returns an empty string.

Solution 2:

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, "\:\"\"")); 

Solution 3:

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){

    (functionremoveNull(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');

Solution 4:

For anyone still looking for a solution.

Used this in my angular 2 app to remove all null values returned by my db query.

Create an angular 2 function in the component

    replacer(i, val) {
     if ( val === null ) 
     { 
        return""; // change null to empty string
     } else {
        returnval; // return unchanged
     }
    }

Or Javascript function

    function replacer(i, val) {
     if ( val === null ) 
     { 
        return""; // change null to empty string
     } else {
        returnval; // return unchanged
     }
    }

Then use the function in JSON.stringify method

JSON.stringify(result, this.replacer)

Solution 5:

Here is a simple code that will convert all null values into an empty string

let myObject = {
  "id":1,
  "name": "Ali",
  "address":null,
  "phone":null,
  "age":22
}
Object.keys(myObject).map(function (key, index) {
                if (myObject[key] == null) {
                    myObject[key] = "";
                }
            });
console.log(myObject); 

// output/* {
  "id": 1,
  "name": "Ali",
  "address": "",
  "phone": "",
  "age": 22
}  */

Post a Comment for "Replace Null Values To Empty Values In A Json Object"