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
inst
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;
}
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');
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, "\:\"\""));
function returnblank(item){
if(item == null){
return "";
}else{
return item;
}
}
Your function should be like this:
function (key, value) {
return (value == null) ? "" : value
}
Checks null
and undefined
values and returns an empty string
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