1

I've tried several answers posted in the site like:

How to check if JSON return is empty with jquery

And no one is working for me.

 xhr.onload = function(){
              detalles = xhr.responseText;
              console.log("log : "+detalles);
   ....
   }

Console output:

log : [0]

Firefox debugger network tab shows JSON 0: 0

Any help provided will be much appreciated.

EDIT - Adding some more code to extend the context

xhr.onload = function(){
                  detalles = xhr.responseText;
                  console.log(detalles);

                    if((!$.trim(detalles))||($.isEmptyObject(detalles))||(!detalles[0])){
                        console.log("ok");
                        $("#graficohist").html("No info available");
                        triggerLoader();
                    }
Community
  • 1
  • 1
lenord
  • 1,151
  • 1
  • 10
  • 16

2 Answers2

2

You can simply make a function to test in the object is empty

var myObj = {"key" : "value"};
checkEmptyJson = function(myObj){
var count = 0;
for(var key in myObj){
count++;
break;
}
 if(count == 0){
  return false; // object is empty
 }else{
  return true; // object is not empty
 }
}
var result = checkEmptyJson(myObj);
console.log(result);

In your context we can use it as

hasDetallesData =  checkEmptyJson(detalles); // true if Detalles has data
Mitesh Pant
  • 524
  • 2
  • 15
  • 1
    This is a good solution but I believe there should be a one liner or simpler method to retrieve a boolean whenever the JSON response is null and I can't find it. Nevertheless I'll try and test your solution. Thanks for your reply. – lenord Jan 25 '17 at 16:52
1

I suggest to try this

var obj = JSON.parse(text);

to convert your json to a javascript object, and then you can make a print it with

console.log(obj)

to see what you have inside the obj

Sal-laS
  • 11,016
  • 25
  • 99
  • 169