2

How to remove the null value in json string using jquery

var jsonstring=[null,null,{"rank":"23","credit":"10"},null,null,{"rank":"26","credit":"10"},null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,{"rank":"31","credit":"05"}]

vengatesh rkv
  • 327
  • 2
  • 16

3 Answers3

4
var arr = JSON.parse(json_string);
arr = arr.filter(function(n){ return n }); 
json_string = JSON.stringify(arr)
Youssef
  • 1,033
  • 8
  • 16
2

Use like this

(function filter(obj) {
    $.each(obj, function(key, value){
        if (value === "" || value === null){
            delete obj[key];
        } else if (Object.prototype.toString.call(value) === '[object Object]') {
            filter(value);
        } else if ($.isArray(value)) {
            $.each(value, function (k,v) { filter(v); });
        }
    });
})(sjonObj);
Rex Rex
  • 1,030
  • 1
  • 8
  • 29
1

You should use array access notation please see the below code

    delete sjonObj[key];


 $.each(sjonObj, function(key, value){
 if (value === "" || value === null){
    delete sjonObj[key];
  }
 });

Thanks

Joseph
  • 1,054
  • 1
  • 11
  • 25