is JSON Object empty

B

bfrederi

I am writing some javascript that gets a JSON object embedded into a
<script/> tag in my html.
Sometimes the JSON object will look like this:
JSONthing = {"boundingBoxes": [{"y1": "0.571", "x2": "0.447", "x1":
"0.408", "word": "crimin", "y2": "0.574"}]}
and sometimes it will be empty:
JSONthing = {}
What I need to know is how to test if the JSON object is empty, across
all browsers. So far I can't find anything that works in all browsers.
 
L

Lasse Reichstein Nielsen

bfrederi said:
I am writing some javascript that gets a JSON object embedded into a
<script/> tag in my html.
Sometimes the JSON object will look like this:
JSONthing = {"boundingBoxes": [{"y1": "0.571", "x2": "0.447", "x1":
"0.408", "word": "crimin", "y2": "0.574"}]}
and sometimes it will be empty:
JSONthing = {}
What I need to know is how to test if the JSON object is empty, across
all browsers. So far I can't find anything that works in all browsers.

What do you mean by "all browsers"? Netscape 4? 3? 2? Or just all
modern browsers and Internet Explorer?

You can try:

function isEmpty(object) {
for(var i in object) { return true; }
return false;
}

This returns true if the object has any enumerable property. The
object generated by "{}" in a default Javascript setting will have no
enumerable properties (it has no properties itself, and the properties
inherited from Object.prototype are all non-enumerable). An object
generated by an object literal with properties will have those properties
as enumerable.

It uses only features that was present in JavaScript 1.0 (Netscape 2),
so compatability should not be a problem.

Notice, however, that some libraries infect the Object.prototype with
enumerable properties, which would make this test fail (always return
true). I recommend dropping such libraries (they should be reported as
"does not play well with others").

/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,145
Messages
2,570,826
Members
47,371
Latest member
Brkaa

Latest Threads

Top