2

I have a bunch of data in a JSON that I need to parse, but some of them does not exist.

Hence, I currently, have the following try/catch(e) but is there a more elegant way to do so?

for (var u = 0; u < 100; u++) {
      try {
        var reactions = JSON.parse(dataParsed.data[u].reactions.summary.total_count)
      } catch (err) {
        console.log(err)
        var reactions = 0
      }
      try {
        var comments = JSON.parse(dataParsed.data[u].comments.summary.total_count)
      } catch (err) {
        var comments = 0
      }
      try {
        var shares = JSON.parse(dataParsed.data[u].shares.count);
      } catch (err) {
        var shares = 0
      }

      postArray.push({
        "id": dataParsed.data[u].id,
        "message": dataParsed.data[u].message,
        "createdTime": dataParsed.data[u].created_time,
        "fullPicture": dataParsed.data[u].full_picture,
        "reactions": reactions,
        "comments": comments,
        "shares": shares
      })
}
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
turtlepower
  • 708
  • 1
  • 7
  • 18
  • is `dataParsed` already parsed (like the name suggests), or not? If it is, why do `JSON.parse` again? If it is not, shouldn't you parse only the first part -- the JSON string at the top level (i.e. `JSON.parse(dataParsed).data[u].comments.summary.total_count`)? – Thilo Jul 07 '19 at 03:11
  • Show us what `dataParsed` looks like for better answers. In particular, if it is already an object, or still a String. – Thilo Jul 07 '19 at 03:16

3 Answers3

3

You can use && (short circuiting ) and || (default vlaue)

var reactions = dataParsed && dataParsed.data[u] &&  dataParsed.data[u].reactions && dataParsed.data[u].reactions.summary && dataParsed.data[u].reactions.summary.total_count || 0

There's a proposal for optional chaining and Nullish Coalescing

var reactions = dataParsed?.data[u]?.reactions?.summary?.total_count ?? 0
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • Given that the OP was `var reactions = JSON.parse(...)` it might be better if the default value is valid JSON, otherwise you're just changing one error for another. ;-) – RobG Jul 07 '19 at 04:21
1

Make a function:

function safeParse(propStr) {
  let r = 0;
  try {
    r = propStr.split(/\.|\[|\]/g).reduce((a, c) => a[c], {});
  } catch(e) {}
  return r;
}

var reactions = safeParse("dataParsed.data[u].reactions.summary.total_count");
var comments = safeParse("dataParsed.data[u].comments.summary.total_count");
var shares = safeParse("dataParsed.data[u].shares.count");
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

Just use value|0 to catch the value via binary operation. If value exists, then it will return value if not, then it will return 0

Veggiebob
  • 11
  • 2