Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null / empty json how to check for it and not output?

I've got a json encoded dataset that I retrieve via ajax. Some of the data points I'm trying to retrieve will come back us null or empty.

However, I don't want those null or empty to be displayed to the end user, or passed on to other functions.

What I'm doing now is checking for

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

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

like image 495
pedalpete Avatar asked Feb 08 '09 02:02

pedalpete


People also ask

How do you check is JSON empty or not?

Using JSON.If we stringify the object and the result is simply an opening and closing bracket, we know the object is empty.

How do I check if a JSON property is null?

if (record.has("my_object_name") && ! record. isNull("my_object_name")) { // Do something with object. }

Is an empty JSON null?

"JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types." "The JSON empty concept applies for arrays and objects...Data object does not have a concept of empty lists. Hence, no action is taken on the data object for those properties."

Is Empty response valid JSON?

If you have request or response type JSON, then JSON parsing will happen. The shortest valid JSON document is a single digit number. Empty document is no valid JSON and therefore errors out.


2 Answers

Since JSON is simply a data format, there really is no way to know which of your data members will be null unless you explicitly check them. You can always refactor your code to make it more compact and easier to read, but you will have to check each item explicitly if you do not know beforehand which will be null and which will contain data.

While I don't know what your code is supposed to do, here is an example of how you might refactor 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
}
like image 186
Kevin Babcock Avatar answered Oct 30 '22 04:10

Kevin Babcock


I'm not completely sure of what you want to do... you say that you don't want to pass them on to other functions so I assume you want to delete 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 check for hasOwnProperty is to make sure that it isn't some property from the property chain.

like image 42
some Avatar answered Oct 30 '22 06:10

some