从 JSON 对象中删除空括号

Remove empty brackets from a JSON object

本文关键字:删除 JSON 对象      更新时间:2023-09-26

我想从 JSON 字符串中删除匹配的元素{},{}

输入 : "test": [{},{},{},{},{},{},{}],

输出 : "test": [],

为此,我尝试了:

var jsonConfig = JSON.stringify(jsonObj);
var jsonFinal = jsonConfig.replace(/[{},]/g, ''); // Remove global
var jsonFinal = jsonConfig.replace(/[{},]/, ''); // Remove brackets
console.log(jsonFinal);

等等。

如何仅从 JSON 中删除这些元素集而不影响其他括号和逗号?

请勿尝试使用字符串操作函数修改 JSON。

始终解析 JSON,转换数据,然后重新stringify为 JSON。

编辑:此答案解决了您的评论,即input数据对象将包含输出中应存在的其他潜在键。

// a couple of procedures to help us transform the data
const isEmptyObject = x => Object.keys(x).length === 0;
const not = x => ! x;
const comp = f => g => x => f (g (x));
const remove = f => xs => xs.filter (comp (not) (f));
// your input json
let json = '{"test": [{},{},{"x": 1}], "test2": [{},{}], "a": 1, "b": 2}';
// parsed json
let data = JSON.parse(json);
// transform data
let output = JSON.stringify(Object.assign({}, data, {
  // remove all empty objects from `test`
  test: remove (isEmptyObject) (data.test),
  // remove all empty objects from `test2`
  test2: remove (isEmptyObject) (data.test2),
}));
// display output
console.log(output); // '{"test":[{"x":1}],"test2":[],"a":1,"b":2}'

>我喜欢 ES2015 的答案@naomik。
这是另一种选择:

/**
 * Remove empty objects or arrays
 * @param  {Object, Array} obj: the object to which remove empty objects or arrays
 * @return {Any}
 */
const removeEmptyObject = (function() {
  const isNotObject = v => v === null || typeof v !== "object";
  const isEmpty = o => Object.keys(o).length === 0;
  return function(obj) {
    if (isNotObject(obj)) return obj;
    if (obj instanceof Array) {
      for (let i = 0; i < obj.length; i += 1) {
        if (isNotObject(obj[i])) continue;
        if (isEmpty(obj[i])) obj.splice(i--, 1);
        else obj[i] = removeEmptyObject(obj[i]);
      }
    }
    else {
      for (let p in obj) {
        if (isNotObject(obj[p])) continue;
        if (!isEmpty(obj[p])) obj[p] = removeEmptyObject(obj[p]);
        if (isEmpty(obj[p])) delete obj[p];
      }
    }
    return obj;
  }
}());

现在让我们测试代码:

var json = '{"test": [{},{},{"x": 1}], "test2": [{},{}], "test3":[[],[1,2,3],[]], "a": 1, "b": 2}';
var data = JSON.parse(json); //Object
var output = removeEmptyObject(data);
console.log(output);
console.log(removeEmptyObject(9));
console.log(removeEmptyObject(null));
console.log(removeEmptyObject({}));

你应该处理实际对象而不是字符串。

如果这样做,则可以遍历对象并检查它是否具有任何属性。如果没有,您可以将其删除。

for(var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
       //remove here
    }
}

撇开字符串操作是否是整理 JSON 数据的最佳方式的问题不谈,您之前的尝试将删除所有大括号和逗号,因为正则表达式中的[]表示"匹配这些括号中包含的任何字符"。 如果你试图将它们视为文字字符,则需要对它们进行转义:'[']

你想要类似 .replace(/{},?/g,"") 的东西(这意味着"匹配字符串{}或字符串{},的所有实例 - 问号使前面的字符成为可选匹配项)。

(当然,这会从字符串中删除所有空对象,并且有可能在给定输入(如"foo: {}, bar: {}")的情况下创建无效的JSON——因此,仅当您确定数据永远不会包含故意的空对象时才使用它。