0

I'm trying to minimize duplicate code like:

let name = "";
try {
  name = data[" "][0][" "][0][" "][0][" "][1][" "][0][" "][1]["C"];
} catch (error) {
  if (error instanceof TypeError) {
    console.log("name TypeError");
  }
}

I thought about creating a function that I can pass it the JSON parameter (data variable) with the path (i.e. data[" "][0][" "][0][" "][0][" "][1][" "][0][" "][1]["C"]) so the error handling will be in the function and I will not have to duplicate the try catch every time (I extract data from that JSON a lot).

But I cannot find a proper way to do it. Would appreciate any help!

Nirgn
  • 1,879
  • 4
  • 23
  • 28

1 Answers1

1

You could be using something like JsonPath: https://www.npmjs.com/package/JSONPath This library handles all the exceptions itself.

MarengoHue
  • 1,789
  • 13
  • 34