[英]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. 我是javascript新手,遇到一个问题,我需要从json文件中删除所有null值。 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]} ".
正如我在json文件之前所说的那样,我只是遇到一个问题,可以使用JSON.stringify来获取它,并通过使用删除null的代码来获取此“ {\\”名称\\“:\\” 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: Json文件:
{
"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: JSON.parse
和JSON.stringify
接受JSON.stringify
函数来修改值:
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 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.