Null / empty json, how to check it and not output it?

I have a coded json dataset that I get through ajax. Some of the data points that I am trying to recover will return to us with zero or empty.

However, I do not want those that are empty or empty to be displayed to the end user or passed to other functions.

Now i check

     if (this.cityState! = 'null') {
             // do some stuff here
 }

However, for each line, I find myself through several if statements, and this seems very inefficient. Is there a better way to do this?

+8
json javascript
source share
4 answers

Since JSON is just a data format, there is no way to know which of your data members will be null unless you explicitly check them. You can always reorganize your code to make it more compact and easier to read, but you will need to check each element explicitly if you do not know in advance which will be null and which will contain data.

While I don't know what your code should do, here is an example of how you can reorganize it to make it more compact:

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

I'm not quite sure what you want to do ... you say you don't want to pass them to other functions, so I assume that you want to remove them:

 var data = {a:"!",b:"null", c:null, d:0, e:"", hasOwnProperty:"test"}; var y; for (var x in data) { if ( Object.prototype.hasOwnProperty.call(data,x)) { y = data[x]; if (y==="null" || y===null || y==="" || typeof y === "undefined") { delete data[x]; } } } 

The test for hasOwnProperty is to make sure that it is not a property in the property chain.

+4
source share

Or you can just use

 int data=0; try{ data=json.getInt("Data"); }catch(Exception e){ data=anydefaultdata; } 
+2
source share

I get a response from the server where the key value in JSON is empty. The following is an example.

 { "ShowMoreTransactions": false, "IsAutoScrollQuickSearch": } 

Can someone tell me how to parse such an answer as JSON throws an error.

0
source share

All Articles