简体   繁体   中英

Remove null values from json file javascript

I am new to javascript and I have encountered a problem I need to remove all null values from a json file. But I have not been able to get it I have tried different methods that I found on the site but they do not work for me. One of the ways I found below. I just have a problem as I said before the json file I get it with JSON.stringify and by using the code that removes null I get this "{\\" name \\ ": \\" Ann \\ " , \\ "children \\": [null, {\\ "name \\": \\ "Beta \\", \\ "children \\": [null, null, null]}, null]} ".

function Parent(name){
    this.name = name;
    this.children=new Array(null,null,null);
}

Parent.prototype.getName = function(){
return this.name;
};

Parent.prototype.setName = function(name) { 
 this.name=name; 
};

Parent.prototype.getChildren = function(){
 return this.children;
};

Parent.prototype.setChildren = function(parent) { 
 this.children=parent; 
};

var parent = create(aux,new Parent(""));// This method create tree parent
var o = parent;
j = JSON.stringify(o, (k, v) => Array.isArray(v) 
       && !(v = v.filter(e => e !== null && e !== void 0)).length ? void 0 : v, 2 )
     alert (j);

Json file:

{
  "name": "Ann",
  "children":
  [
    null,
    {
      "name": "Beta",
      "children":
      [
        null,
        null,
        null
      ]
    },
    null
  ]
}

What I expect:

{
  "name": "Ann",
  "children":
  [
    {
      "name": "Beta"
    }
  ]
}

JSON.parse and JSON.stringify accept replacer function to modify the values:

 j = '{ "name": "Ann", "children": [ null, { "name": "Beta", "children": [ null, null, null ] }, null ] }' o = JSON.parse(j, (k, v) => Array.isArray(v) ? v.filter(e => e !== null) : v ) console.log( o ) 

 o = { "name": "Ann", "children": [ null, { "name": "Beta", "children": [ null, null, null ] }, null ] } j = JSON.stringify(o, (k, v) => Array.isArray(v) ? v.filter(e => e !== null) : v, 2 ) console.log( j ) 

To remove the empty array too:

 o = { "name": "Ann", "children": [ null, { "name": "Beta", "children": [ null, null, null ] }, null ] } j = JSON.stringify(o, (k, v) => Array.isArray(v) && !(v = v.filter(e => e)).length ? void 0 : v, 2 ) console.log( j ) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM