How to know if a JSONObject contains a key?

Hey guys,

I'm trying to figure out how to know if a JSONObject contains a key. I tried the method myJSON.containsKey("theKey"), but Processing gives me the error "The function containsKey(String) does not exist".

I've also tried "myJSON.has ("theKey")" and it does not work either.

It's getting me crazy!!

Thanks for any help!

Tagged:

Answers

  • What type is myJSON?

  • Maybe you need to use parseJSONObject first?

  • edited December 2015 Answer ✓

    well, each json interface is different (depending if its about weather, movies or animals... e.g.)

    each json interface holds different keys

    so either

    • you have the documentation of the specification of that json interface

    • or you use println to just print out the whole json string. Then you can look up the keys you need. And the structure, often there are json-arrays or other json-objects embedded

    when you ask for a key that doesn't exist the var should be null. So you can write your own check function

    boolean containsKey(JSONObject jsonObj, String key) {
    
        if (jsonObj==null) 
            println("jsonObj was null"); 
            return false; 
        }    
        if (key==null) 
            return false; 
    
        if (key.equals("")) 
            return false; 
    
        String name = null;
    
        name = jsonObj.getString(key);
    
        if (name==null) 
            return false; 
         else 
            return true; 
    
    
    }
    
  • @Chrisir: we first need to establish where the json is coming from and if it has been parsed into a json object...

  • Thanks for answering. The error was my bad...

    I provide the JSON from a client sketch.

Sign In or Register to comment.