The JSON Collection object I'm receiving looks like this:
[{"foo1":"bar1", "foo2":"bar2", "problemkey": "problemvalue"}]
What I'm trying to test for is the existence of problemvalue
. If problemvalue
returns a JSON Object, I'm happy. If it doesn't, it will return as {}
. How do I test for this condition? I've tried several things to no avail.
This is what I've tried thus far:
// if (obj.get("dps") == null) { //didn't work
// if (obj.get("dps").equals("{}")) { //didn't work
if (obj.isNull("dps")) { //didn't work
System.out.println("No dps key");
}
I expected one of these lines to print "No dps key" because {"dps":{}}
, but for whatever reason, it's not. I'm using org.json
. The jar file is org.json-20120521.jar
.
return Object.keys(obj).length === 0 ; This is typically the easiest way to determine if an object is empty.
If you want to check if your response is not empty try : if ( json. length == 0 ) { console. log("NO DATA!") }
JSON data has the concept of null and empty arrays and objects. This section explains how each of these concepts is mapped to the data object concepts of null and unset.
Object. keys(myObj). length === 0; As there is need to just check if Object is empty it will be better to directly call a native method Object.
obj.length() == 0
is what I would do.
If you're okay with a hack -
obj.toString().equals("{}");
Serializing the object is expensive and moreso for large objects, but it's good to understand that JSON is transparent as a string, and therefore looking at the string representation is something you can always do to solve a problem.
If empty array:
.size() == 0
if empty object:
.length() == 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With