Javascript check json output is empty

白昼怎懂夜的黑 提交于 2019-12-12 05:13:08

问题


If I have data in json like this :

{"items":[{"id":"2049","channel_code":"HBD","channel_name":"HBO HD"}]}

And if you search my data to the server could not find results like this :

{"items":[]}

Of output as above, how do I read that my data does not exist or is empty?

I have written some code that I got but have not found the results I want.

This code :

var data = { Name: "John Doe", Age: 25, Address: null, CityState: "Denver, CO" };
for (member in data) {
if (data[member] != null)
    //Do something
}

or

if (myObject == '') {
   alert('this object is empty');
}

Maybe someone can help me find a way out of this example. Please help


回答1:


To check whether your array is empty, just use the respective length property:

if ( data['items'].length < 1 ) {
   // it's empty
}



回答2:


You want to check if data.items.length > 0. Assuming

var data = {"items":[]};



回答3:


for (member in data) {
if (data[member] != null)
    //Do something
}

code inside for will not run because length of data is 0

if (myObject == '') {
   alert('this object is empty');
}

myObject wont be null because the object actually is there and its an empty array

you should check for myObject.length because its an empty array



来源:https://stackoverflow.com/questions/12932590/javascript-check-json-output-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!