我想从 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/