javascript - Remove empty brackets from a JSON object -
i remove matching elements {},
, {}
json string.
input : "test": [{},{},{},{},{},{},{}],
output : "test": [],
to so, tried :
var jsonconfig = json.stringify(jsonobj); var jsonfinal = jsonconfig.replace(/[{},]/g, ''); // remove global var jsonfinal = jsonconfig.replace(/[{},]/, ''); // remove brackets console.log(jsonfinal);
and many more.
how can remove set of elements json without impacting other brackets , comma?
do not attempt modify json string manipulation functions.
always parse json, transform data, , re-
stringify
json.
edit: answer addresses comment input
data object contain other potential keys should present in output.
// couple of procedures transform 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)); // 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 empty objects `test` test: remove (isemptyobject) (data.test), // remove empty objects `test2` test2: remove (isemptyobject) (data.test2), })); // display output console.log(output); // '{"test":[{"x":1}],"test2":[],"a":1,"b":2}'
Comments
Post a Comment