View Light

HOWTO: Send null value to an AJAX web service with JSON

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:

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:

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"; 
    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:

Hope this helps, enjoy!

Rating: (You must be logged in to vote)
This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit to those who have expressed a prior interest in receiving the included information for research and educational purposes. For more information go to: . If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner.