superslinky February 2016

Remove empty brackets from a JSON object

I would like to remove the matching elements {}, and {} from a JSON string.

Input : "test": [{},{},{},{},{},{},{}],

Output : "test": [],

To do so, I 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 I remove only those set of elements from my JSON without impacting the other brackets and comma?

Answers


Daniel Beck February 2016

Setting aside the question of whether string manipulation is the best way to tidy up JSON data, your earlier attempts would remove all braces and commas, because [] in a regexp indicates "match any of the characters contained inside these brackets". If you were trying to treat those as literal characters, they'd need to be escaped: \[ or \]

You want something like .replace(/{},?/g,"") (which means "match all instances of the string {} or the string {}, -- the question mark makes the preceding character an optional match).

(This would, of course, remove all empty objects from the string, and has the potential to create invalid JSON given input like "foo: {}, bar: {}" -- so only use this if you're certain that your data will never include intentionally empty objects.)


serdem420 February 2016

You should work on the actual object not the string.

If you do, you can loop through the object and check if it has any properties. If it doesn't have any, you can remove it.

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


naomik February 2016

Do NOT attempt to modify JSON with string manipulation functions.

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

EDIT: this answer addresses your comment that the input data object will contain other potential keys that should be present in the output.

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


jherax February 2016

I like the ES2015 answer of @naomik.

Little late, but this is an ES5 alternative:

/* Deletes empty objects from an object/array */
var removeEmptyObjects = (function() {

    var _toString = Object.prototype.toString,
        _isValid = /\[object (?:Object|Array)\]/,
        _isObject = "[object Object]";

    function removeEmptyObjects(obj) {
        var isObj = _toString.call(obj),
            newObj, item;
        //validates object or array
        if (_isValid.test(isObj)) {
            isObj = (isObj === _isObject);
            if (isObj && !Object.keys(obj).length) {
                //is an empty object
                return undefined;
            }
            //initializes object or array
            newObj = isObj ? {} : [];
            for (var prop in obj) {
                //recursively iterates over properties/items
                item = removeEmptyObjects(obj[prop]);
                if (item !== undefined) {
                    //set values for object/array respectively
                    if (isObj) newObj[prop] = item;
                    else newObj.push(item);
                }
            }
        }
        return newObj || obj;
    }

    return removeEmptyObjects;

}());

Now lets test the code:

var json = '{"test": [{},{},{"x": 1}], "test2": [{},{}], "a": 1, "b": 2}';
var data = JSON.parse(json); //Object
var output = removeEmptyObjects(data);

console.log(output);
console.log(removeEmptyObjects(9));
console.log(removeEmptyObjects(null));
console.log(removeEmptyObjects({})); //deleted

Post Status

Asked in February 2016
Viewed 1,281 times
Voted 8
Answered 4 times

Search




Leave an answer