7

I'd like to know the most simple way to detect if a key/field exists in a JSON String.

for example:

if(jsonObject(myJsonString).hasKey("myKey")){

}

I would not prefer to write a lot. I am currently using minimal JSON and it appears it does not have such a function.

Answer: JSONObject jsonObj2 = new JSONObject(message); if(jsonObj2.has("key"));

3
  • Are you using any kind of JSON library?
    – Darkhogg
    Commented Nov 4, 2013 at 19:20
  • 1
    Yes I am! github.com/ralfstx/minimal-json - I cannot seem to find a suitable method!
    – basickarl
    Commented Nov 4, 2013 at 19:20
  • Generally speaking, you'd parse the JSON into it's "object" representation in your language, then ask for the key of interest. Of course, this will not tell you if there is a matching key ten layers deep, but that's rarely worthwhile knowing without other contextual info.
    – Hot Licks
    Commented Nov 4, 2013 at 19:55

3 Answers 3

13

Not sure what you mean exactly by minimal JSON, personally I find the org.json package simple and straightforward (i.e. minimal overhead). It is found here. The org.json.JSONObject class, for example, contains the public boolean has(String key) method, which is used to check if a certain key exists.

0
2

In minimal-json, you'd write:

if (JsonObject.readFrom(myJsonString).get("myKey") != null) {
  ...
}
0

I faced the same problem. obj.has("myKey") was not working for minimalJson.

My solution:

Take your JsonObject obj which has that key and then do the following:

if(obj.get("myKey") != null)

Not the answer you're looking for? Browse other questions tagged or ask your own question.