'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 :

$.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');

Any ideas?



Solution 1:[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:[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:[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){

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

Solution 4:[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 {
        return val; // return unchanged
     }
    }

Or Javascript function

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

Then use the function in JSON.stringify method

    JSON.stringify(result, this.replacer)

Solution 5:[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
}  */

Solution 6:[6]

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

Solution 7:[7]

Underscore mapObject gave me the most compact solution. Here's a complete example:

$ npm install underscore

import _, { map, each } from 'underscore';
var x = {a:null, b:1, c:'c', d:null}
var y = _.mapObject(x, function(val, key) {
            return val || '';
        });
console.log('No nulls:', y)

No nulls: {a:"", b:1, c:"c", d:""}

Solution 8:[8]

Little late to the party buy hey/ho.

The below function is the exact opposite of what you need, so just reverse engineer :D

In order to swap empty string's or strings with spaces in JSON we will need to iterate through the keys and check if a value contains an empty string.

You can complete this, easily with the .trim method. We basically check, if the length of the string trimmed, (without spaces) is equal to 0. If so we will add the same key to our new object but add a null value instead. You could also remove the length in the trim call and check if obj[keys].trim == ''.

      function myFunction(obj){
      const newObj = {}

      for(keys in obj){
      if(obj[keys].trim().length == 0){
      newObj[keys] = null; 
      }
      else{
      newObj[keys] = obj[keys];
      }
   }

   return newObj;

 }

Solution 9:[9]

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;
}

Solution 10:[10]

You can replace null values to empty by below code in java-script

var remove_empty = function ( target ) {
  Object.keys( target ).map( function ( key ) {
    if ( target[ key ] instanceof Object ) {
      if ( ! Object.keys( target[ key ] ).length && typeof target[ key ].getMonth !== 'function') {
        target[ key ] = "";
      }
      else {
        remove_empty( target[ key ] );
      }
    }
    else if ( target[ key ] === null ) {
       target[ key ] = "";
    }
  } );
  return target;
};

you can read more about Object.keys

Solution 11:[11]

function returnblank(item){
  if(item == null){
    return "";
  }else{
    return item;
  }
}