19

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?

5
  • Your code says that if the value is an empty string, then the empty string should be returned; if it's anything else, then the value should be returned as-is. Thus, it's exactly equivalent to just return value; Commented Mar 5, 2014 at 16:30
  • 3
    Shouldn't you compare it to null? Commented Mar 5, 2014 at 16:31
  • You realize that data doesn't really change even if you stringify the object like that ? Commented Mar 5, 2014 at 16:35
  • @Kuma: Where did you get that code from? It doesn't appear in the revision history. Commented Mar 7, 2014 at 1:26
  • @BoltClock, I believe it was edited first by him (to narrow down the code) before I applied my edit. See one answer here that contains the same code. Commented Mar 7, 2014 at 1:35

12 Answers 12

45

Your function should be like this:

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

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

Sign up to request clarification or add additional context in comments.

7 Comments

value == null will be true when value is either null or undefined, so there's no need for any further comparison.
@Anthony - As I commented on the answer, this doesn't change anything, strings are immutable, and the object surely isn't updated just because you decided to stringify it.
This could be refactored to return value || "";
Should not use return value || "" . 0 or false will be empty string, either.
@KevinFarrugia not that, for reason that @kook mentioned, but you could do null-coalescing: return value ?? '' without those weird side effects.
|
21

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

6 Comments

Don't you think it would be better to use the built in replacer argument rather than a string replace ?
I don't see a reason why this would be bad idea, in cases where we use serialized JSON string anyway and when it wouldn't affect performance
But JSON.stringify has a built in replacer as the second argument, which is what the OP is using. Don't you think it would be a better idea to use the built in replacer argument than to create your own for no apparent reason ?
Yeah, you're right. I think about this as clean on-line-solution, but I definitely agree with you that built-in solutions should always have priority over custom solutions.
This is a horrible idea.
|
8

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

Comments

2

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)

Comments

2

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

Comments

1

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

Comments

0

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

Comments

0

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;

 }

Comments

0

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
-1

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

Comments

-1

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

Comments

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

2 Comments

A little explanation would not hurt.
Please try and add an explanation to your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.