How to check if a JSON key exists?

JavaAndroidJson

Java Problem Overview


So, I get some JSON values from the server but I don't know if there will be a particular field or not.

So like:

{ "regatta_name":"ProbaRegatta",
  "country":"Congo",
  "status":"invited"
}

And sometimes, there will be an extra field like:

{ "regatta_name":"ProbaRegatta",
  "country":"Congo",
  "status":"invited",
  "club":"somevalue"
}

I would like to check if the field named "club" exists so that at parsing I won't get

> org.json.JSONException: No value for club

Java Solutions


Solution 1 - Java

JSONObject class has a method named "has":

http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)

> Returns true if this object has a mapping for name. The mapping may be NULL.

Solution 2 - Java

You can check this way where 'HAS' - Returns true if this object has a mapping for name. The mapping may be NULL.

if (json.has("status")) {
   String status = json.getString("status"));
}

if (json.has("club")) {
   String club = json.getString("club"));
}

> You can also check using 'isNull' - Returns true if this object has no > mapping for name or if it has a mapping whose value is NULL.

if (!json.isNull("club"))
    String club = json.getString("club"));

Solution 3 - Java

you could JSONObject#has, providing the key as input and check if the method returns true or false. You could also

use optString instead of getString:

> Returns the value mapped by name if it exists, coercing it if > necessary. Returns the empty string if no such mapping exists

Solution 4 - Java

just before read key check it like before read

JSONObject json_obj=new JSONObject(yourjsonstr);
if(!json_obj.isNull("club"))
{
  //it's contain value to be read operation
}
else
{
  //it's not contain key club or isnull so do this operation here
}

isNull function definition

Returns true if this object has no mapping for name or
if it has a mapping whose value is NULL. 

official documentation below link for isNull function

http://developer.android.com/reference/org/json/JSONObject.html#isNull(java.lang.String)

Solution 5 - Java

You can use has

public boolean has(String key)

Determine if the JSONObject contains a specific key.

Example

JSONObject JsonObj = new JSONObject(Your_API_STRING); //JSONObject is an unordered collection of name/value pairs
				
if (JsonObj.has("address")) { 
    //Checking address Key Present or not
    String get_address = JsonObj .getString("address"); // Present Key
}
else {
    //Do Your Staff
}

Solution 6 - Java

A better way, instead of using a conditional like:

if (json.has("club")) {
    String club = json.getString("club"));
 }

is to simply use the existing method optString(), like this:

String club = json.optString("club);

the optString("key") method will return an empty String if the key does not exist and won't, therefore, throw you an exception.

Solution 7 - Java

Json has a method called containsKey().

You can use it to check if a certain key is contained in the Json set.

File jsonInputFile = new File("jsonFile.json"); 
InputStream is = new FileInputStream(jsonInputFile);
JsonReader reader = Json.createReader(is);
JsonObject frameObj = reader.readObject();
reader.close();

if frameObj.containsKey("person") {
      //Do stuff
}

Solution 8 - Java

Try this:

let json=yourJson

if(json.hasOwnProperty(yourKey)){
	value=json[yourKey]
}

Solution 9 - Java

Try this

if(!jsonObj.isNull("club")){
    jsonObj.getString("club");
}

Solution 10 - Java

I used hasOwnProperty('club')

var myobj = { "regatta_name":"ProbaRegatta",
    "country":"Congo",
    "status":"invited"
 };

 if ( myobj.hasOwnProperty("club"))
     // do something with club (will be false with above data)
     var data = myobj.club;
 if ( myobj.hasOwnProperty("status"))
     // do something with the status field. (will be true with above ..)
     var data = myobj.status;

works in all current browsers.

Solution 11 - Java

You can try this to check wether the key exists or not:

JSONObject object = new JSONObject(jsonfile);
if (object.containskey("key")) {
  object.get("key");
  //etc. etc.
}

Solution 12 - Java

I am just adding another thing, In case you just want to check whether anything is created in JSONObject or not you can use length(), because by default when JSONObject is initialized and no key is inserted, it just has empty braces {} and using has(String key) doesn't make any sense.

So you can directly write if (jsonObject.length() > 0) and do your things.

Happy learning!

Solution 13 - Java

You can use the JsonNode#hasNonNull(String fieldName), it mix the has method and the verification if it is a null value or not

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdam VarhegyiView Question on Stackoverflow
Solution 1 - JavaPX DeveloperView Answer on Stackoverflow
Solution 2 - JavaNiraliView Answer on Stackoverflow
Solution 3 - JavaBlackbeltView Answer on Stackoverflow
Solution 4 - JavaStack Overflow UserView Answer on Stackoverflow
Solution 5 - JavaIntelliJ AmiyaView Answer on Stackoverflow
Solution 6 - JavafuzzKittyView Answer on Stackoverflow
Solution 7 - JavaUdana MethmalView Answer on Stackoverflow
Solution 8 - JavaAishwaryaView Answer on Stackoverflow
Solution 9 - JavaR9JView Answer on Stackoverflow
Solution 10 - JavacdturnerView Answer on Stackoverflow
Solution 11 - JavaDorus BlankenView Answer on Stackoverflow
Solution 12 - JavaGurinderView Answer on Stackoverflow
Solution 13 - JavaTiago CoelhoView Answer on Stackoverflow