hasOwnProperty to test for existence of key in json file?

Is there a way to test for the existence of a json key in Monkey C? for instance, this is my data

{
"amt": "10.00",
"email": "[email protected]",
"merchant_id": "sam",
"mobileNo": "9874563210",
"orderID": "123456",
"passkey": "1234"
}

I want to check for the existence of the key "merchant_id"

  • let's say the above is in a dictionary represented by "data"

    if(data["merchant_id"]!=null) {

      System.println("id="+data["merchant_id"]);

    }

  • What is the best way to check for the non-existence of a key?  if I use 

    if ( data["merchant_id"] == null ) {

    it just evaluates to whatever the "merchant_id" is, so in this case, I could try the following, which does work...  but it doesn't seem that intuitive.  Also, it's giving me a problem when I try to check for the existence of an object.  my data is:

    {

    "location" = "city",

    "event" = { "type" = "race" , "miles" = "3.0" }

    }

    if ( ! (data["event"] instanceof Toybox.Lang.Object) ) {
            error_message = 1;
    } else {

           // test absence of other keys

    }

    this doesn't seem to work, any tips?  thanks in advance!

  • I do something similar in a number of things get data back from a makeWebRequest, where the json data is in a dictionary.

    Does merchant_id exist but it's just an empty string or something?

    What do you see when you just do

    System.println("data="+data);

    If your data is just a string, you could always do

    data.find("merchant_id") and check the result of that.

  • As @jim_m_58 pointed out, the JSON data is represented as a Dictionary (Toybox.Lang.Dictionary). That class has a method named hasKey() that does exactly what you want.

    For most cases, you can tell if the JSON data has a key by checking if the value associated with that key is null or not:

    var merchant_id = data["merchant_id"];
    if (merchant_id != null) {
        // there was a merchant_id key, merchant_id is the value
    } else {
        // there was no merchant_id key, or there was one and the value was null
    }

  • it just evaluates to whatever the "merchant_id" is, so in this case, I could try the following, which does work... 

    I don't understand why you need to check instanceof. In most cases, if you want to know if a value exists for a key, you can just access that value by name. As mentioned above, data["event"] would return null if there is no key with the name "event" or if the value associated with that key is null... if the value cannot be null then you can use that expression to tell if the key exists or not and get the value for it in one step.

    If the value can be null, and you want to differentiate null from not found, you have to use data.hasKey("event"). This is typically not necessary.

  • This should work:

    if(data["event"]!=null) {
      System.println(data["event"]["type"]);
    }