Skip to content

Throwing NOT_FOUND as error instead? #14

Description

@arcataroger

Hi and thanks for this script! Was super helpful.

I made a minor tweak so that it would return an actual error in the cell instead of the NOT_FOUND string. This makes it work better with IFERROR():

function getJsonValue(path, obj) {
  function cleanObjPart(s) {
    // Handle the case when processing an array element (e.g. "jobs[0]")
    var re = /(\w+)\s*\[\s*(\d+)\s*\]\s*/;
    var match = re.exec(s);
    var objPart;
    if (match != null) {
      var elem1 = match[1];
      var index = parseInt(match[2], 10);
      objPart = obj[elem1][index];
    }
    else {
      objPart = obj[s];
    }
    return objPart;
  }

  var NOT_FOUND = "notFound";
  var parts = path.split(/(?!\B"[^"]*)\.(?![^"]*"\B)/);
  var part;
  var last = removeDoubleQuotes(parts.pop());
  while ((part = parts.shift())) {
    part = removeDoubleQuotes(part);
    var objPart = cleanObjPart(part);
    if (typeof objPart != "object") throw new Error(NOT_FOUND);
    obj = objPart;
  }

  var r = cleanObjPart(last);
  if (r === undefined) 
  {throw new Error(NOT_FOUND)}
  else {return r}
}

Is that helpful at all?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions