HOWTO: Send null value to an AJAX web service with JSON
Posted: 12/21/2010 11:34:43 AM
By: Comfortably Anonymous
Times Read: 2,069
0 Dislikes: 0
Topic: Programming: jQuery/Javascript

Sending a null value in JSON is really easy, but it seems like every time you go to look up how to actually represent a null value in a JSON call to an AJAX web service you instead end up with a bunch of discussion on using JSON.parse / JSON.stringify and helper methods to do just that. [No slam on using the JSON object, it's extremely helpful, just some times you don't need it.]

But sometimes you just need to know "How do I represent a NULL value?" or "Why does the web service keep choking on my null values?"

It's more of a mental adjustment than anything super tricky.

Typically when you run into this issue, you've been attempting to build your JSON string using variables. Something like:

var x = 22;
var y = null;

var json = "{"; // Open bracket
json += "'valX':'" + x + "',"; // Set value of X
json += "'valY':'" + y + "'"; // Set value of Y
json += "}"; // Close bracket

Which gives you a resulting JSON string of:
{'valX':'22','valY':'null'}

This will cause your web service to choke on the the value assigned to valY. Why? Because you are passing the null value as a string. (See the 'null' there? Yep, it's got single quotes around it. That's the problem.)

To pass a null value is easy, just don't put it in quotes!! Easy as that, same thing only no quotes around null values:
{'valX':'22','valY':null}

Your web service will now happily accept your new value. :)

While there's probably better ways to handle nulls, I just use an easy brute-force approach with a NullCheck() function:

function NullCheck(value)

  if (value == null)
    return "null"; 
  else
    return "'" + value + "'"; // Wrap non-null values in single quotes
}

I use it inline when building my JSON string: (Above example modified to use NullCheck())

var x = 22;
var y = null;

var json = "{"; // Open bracket
json += "'valX':" + NullCheck(x) + ","; // Set value of X
json += "'valY':" + NullCheck(y) ; // Set value of Y
json += "}"; // Close bracket

Which outputs:
{'valX':'22','valY':null}

Hope this helps, enjoy!

Rating: (You must be logged in to vote)