javascript - 从 JSON 对象中删除空括号

标签 javascript jquery json regex replace

我想从 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 中仅删除这组元素而不影响其他括号和逗号?

最佳答案

Do NOT attempt to modify JSON with string manipulation functions.

ALWAYS parse the JSON, transform the data, and re-stringify to JSON.

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

// 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}'

关于javascript - 从 JSON 对象中删除空括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35275641/

相关文章:

Javascript:脚本在函数调用时终止

javascript - 当双击广告位于 Flash 中时,自定义滚动无法在 Chrome Mac 上正常工作

javascript - 使用 jquery 文件上传保持文件顺序

javascript - Jquery 'mouseover' 仅在内容加载之前

javascript - 单击按钮时函数不会重新呈现

javascript - $refs 内的 ref 数组在 mounted() 内取消定义

javascript - setTimeout 在 Javascript 中触发两次或不触发

python - 如何将 JSON 数据转换为 Python 对象?

c# - 使用自定义列名称将 C# 类序列化为 JSON 字符串

php - Android - 如何使用 PHP 从 MySQL 数据库获取响应?