Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 323
SoCkEt7 Avatar asked Mar 05 '14 16:03

SoCkEt7


People also ask

Can JSON values be empty?

JSON data has the concept of null and empty arrays and objects.

How do you handle a null response in JSON?

You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.

Is empty string null in JSON?

Yes, JSON has the null value (which is indeed treated as a value, not as the absence of value), and the empty string, and they are different.

Should JSON include null values?

You should definitely include it if there is any need to distinguish between null and undefined since those have two different meanings in Javascript. You can think of null as meaning the property is unknown or meaningless, and undefined as meaning the property doesn't exist.


2 Answers

Your function should be like this:

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

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

like image 63
Amin Abu-Taleb Avatar answered Sep 18 '22 23:09

Amin Abu-Taleb


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, "\:\"\"")); 
like image 37
gradosevic Avatar answered Sep 18 '22 23:09

gradosevic