Best way to check if JSON response is empty or null

I'm just wondering if this is the best way to check if a JSON response is empty or NULL.

This is what I did so far. With this way, how would it figure out which JSON key is actually empty, and which is full, then how would it submit the correct one. That's why I was thinking of the second option. Am I just super over-thinking this?

if ((data.city.length > 0) || (data.region.length > 0) || (data.country.length > 0)) {
    $('#city').empty().append(data.city);
    $('#region').empty().append(data.region);
    $('#country').empty().append(data.country);
} else {
    $('#city').empty().append('No Info Available');
    $('#region').empty().append('No Info Available');
    $('#country').empty().append('No Info Available');
}

But then it got me thinking if this way would be better, it would be a lot longer though. Thoughts on this?

if ((data.city.length > 0) {
    $('#city').empty().append(data.city);
} else {
    $('#city').empty().append('No Info Available');
}

if ((data.country.length > 0) {
    $('#country').empty().append(data.country);
} else {
    $('#country').empty().append('No Info Available');
}

Answers


If that's the pattern you have, and it's consistent

$.each(data, function(key, value) {
    $('#' + key).html(value || 'No Info Available');
});

FIDDLE


Need Your Help

Get last n lines of a file with Python, similar to tail

python file file-io tail logfiles

I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.

Android: How to interact with the contents of a WebView?

android webview

Is there a way to programmatically interact with the contents of a WebView?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.