Best Way To Detect Missing JSON?

Posted on
  • I'm parsing some JSON data from a web-server but in-case the server is down or returns something unexpected I want my code to do something safe. I tried checking if the data was undefined but that produces the error:

    Uncaught Error: Field or method "Hostname" does not already exist, and can't create it on undefined
    

    So next I tried data.hasOwnProperty but this isn't implemented in Espruino's implementation of JSON :/
    So I resorted to try catch which works just fine. Was this the right thing to do or should Espruino have some sort of has for JSON?

  • You should be able to look at the http status code, 200 is ok, anything in the 400 or 500 range is an error.

    If you post your code as an example suggestions can be made.

  • I'd suggest:

    var json;
    try { json = JSON.parse(data); } catch (e) {}
    if (json && "Hostname" in json) {
      ...
    } else {
      // no data
    }
    
  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Best Way To Detect Missing JSON?

Posted by Avatar for MrTimcakes @MrTimcakes

Actions