SoCkEt7
SoCkEt7

Reputation: 2277

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?

Upvotes: 19

Views: 130651

Answers (12)

Manish Pal
Manish Pal

Reputation: 1

Here is the correct way to do it in JS

let data = {
    "msg": "Success",
    "data": [
        {
            "firstName": "Manish",
            "lastName": "Pal",
            "age": 23
        },
        {
            "firstName": "Deepak",
            "lastName": "Gupta",
            "age": null
        }
    ],
    "salary": [
        {
            "id": "1",
            "type": "SD",
            "amount": 1000000
        },
        {
            "id": "2",
            "type": "C",
            "ok": null
        }
    ]
};

let mainResponse = {};

const replaceNull = (value) => {
    return (value == null) ? "" : value
}
//Parse Json and check for null
const removeNullFromJson = (object1, jsonObj) => {
    for (const [key, value] of Object.entries(object1)) {
        if (Array.isArray(value)) {
            jsonObj[key] = [];
            for (let i = 0; i < value.length; i++) {
                jsonObj[key].push(removeNullFromJson(value[i], {}))
            }
        }
        else if (typeof value == "object" && value != null) {
            jsonObj[key] = removeNullFromJson(value, {})
        }
        else {
            jsonObj[key] = replaceNull(value);
        }
    }
    return jsonObj
}

console.log(removeNullFromJson(data, mainResponse))

Upvotes: 0

Adam Foody
Adam Foody

Reputation: 19

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;

 }

Upvotes: 0

Amin Abu-Taleb
Amin Abu-Taleb

Reputation: 4511

Your function should be like this:

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

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

Upvotes: 45

Sanan Ali
Sanan Ali

Reputation: 3427

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
}  */

Upvotes: 1

CFrank
CFrank

Reputation: 1

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:""}

Upvotes: 0

wondim
wondim

Reputation: 727

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

Upvotes: 2

gradosevic
gradosevic

Reputation: 5056

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

Upvotes: 21

Moshood Aminu
Moshood Aminu

Reputation: 291

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)

Upvotes: 2

akshay
akshay

Reputation: 1161

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

Upvotes: -1

Julieto Ompad
Julieto Ompad

Reputation: 15

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

Upvotes: -2

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

Upvotes: -1

adeneo
adeneo

Reputation: 318182

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

Upvotes: 8

Related Questions