【问题标题】:Remove null values from json file javascript从 json 文件 javascript 中删除空值
【发布时间】:2017-12-02 22:15:40
【问题描述】:

我是 javascript 新手,遇到了一个问题,我需要从 json 文件中删除所有空值。但我无法得到它我尝试了我在网站上找到的不同方法,但它们对我不起作用。 我在下面找到的方法之一。我只是有一个问题,正如我在使用 JSON.stringify 得到它的 json 文件之前所说的那样,通过使用删除 null 的代码,我得到了这个 "{\" 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 文件:

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

我的期望:

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

【问题讨论】:

  • 因为我认为您不想删除对象属性。看来您需要 splice 输出数组的空元素。
  • 您确定要修改原始对象吗?我会考虑创建一个新的过滤对象,而不是从原始引用中更新和删除属性
  • @MatiasCicero 放松,它来自一个 JSON 文件,所以一旦解析,它已经是一个副本。
  • 你是否从 JSON.parse 中获取对象?
  • @blex 从方法的角度来看,这可以是任何对象。我只是说该方法的调用者不会得到任何意外行为。如果可能的话,不变性优于可变性。

标签: javascript json


【解决方案1】:

JSON.parseJSON.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 )

也删除空数组:

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 )

【讨论】:

  • 您的解决方案太棒了我只是遇到了一个问题,正如我在 json 文件之前所说的那样,我使用 JSON.stringify 并使用删除空数组的代码来获取它:我得到了这个“{\” name\":\"安\",\"children\":[null,{\"name\":\"Beta\",\"children\":[null,null,null]},null]} ”。我做错了什么?
  • @pete 的值可能不是null,而是undefined 或缺失。尝试更新。
  • 继续做同样的事情很奇怪。随着json被烧毁,它可以工作。但是用 JSON.stringify 获取它是行不通的。 JavaScript 只是想惹恼我。
  • @pete 如果更新后的版本也不起作用,您能否使用重现问题的代码更新您的问题,或者使用MVCE提出单独的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-27
  • 1970-01-01
  • 2013-09-06
  • 1970-01-01
  • 2022-11-16
  • 2016-08-29
  • 1970-01-01
相关资源
最近更新 更多