0

I want to stringify my json but I want to exclude empty nested arrays of objects.

My json looks likt this:

{
  "Fe": {
    "Fh": {
        "a" : 1,
        "b" : "foo"
      },
      "Fb": {
          "Dbs": [
                  {
                    "Nl": "1",
                    "Dt": "red",
                  }
                 ],
          "Dr": [
                  {
                  }
               ]
        }
}

I want to to ignore "Dr" because it is empty.

How can I do it in typescript/Javascript?

Here it the code that I have tried:

const str = JSON.stringify(this.json, replacer);

replacer(key, value) {
  if (value === null || value === {})
   return undefined;
  else
   return value;
 };

Thanks

2 Answers2

1

I came across a similar issue, the accepted answer gave me a great starting point, but I needed something a bit more robust to work with a dynamic structure with deeply nested keys.

Here's what I came up with, thought it might be helpful to share for anyone else who comes across this question:

function isEmpty(value) {
  if (value === null || value === undefined) {
    return true;
  }

  if (Array.isArray(value)) {
    return value.every(isEmpty);
  }
  else if (typeof (value) === 'object') {
    return Object.values(value).every(isEmpty);
  }

  return false;
}

function replacer(key, value) {
  return isEmpty(value)
    ? undefined
    : value;
}

function getPrettyJSON(obj: any) {
  return JSON.stringify(obj, replacer, 2);
}
jeremyalan
  • 4,658
  • 2
  • 29
  • 38
0

You could use a replacer and check if the value is an array and if the items are empty objects.

var object = { Fe: { Fh: { a: 1, b: "foo" }, Fb: { Dbs: [{ Nl: "1", Dt: "red" }], Dr: [{}] } } }, 
    json = JSON.stringify(
        object,
        (k, v) => Array.isArray(v) && v.every(o => JSON.stringify(o) === '{}')
            ? undefined
            : v
    );

console.log(json);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392