As an empty string is not valid JSON it would be incorrect for JSON.parse('') to return null because "null" is valid JSON. e.g.
JSON.parse("null");
returns null. It would be a mistake for invalid JSON to also be parsed to null.
While an empty string is not valid JSON two quotes is valid JSON. This is an important distinction.
Which is to say a string that contains two quotes is not the same thing as an empty string.
JSON.parse('""');
will parse correctly, (returning an empty string). But
JSON.parse('');
will not.
Valid minimal JSON strings are
The empty object '{}'
The empty array '[]'
The string that is empty '""'
A number e.g. '123.4'
The boolean value true 'true'
The boolean value false 'false'
The null value 'null'
As an empty string is not valid JSON it would be incorrect for JSON.parse('') to return null because "null" is valid JSON. e.g.
JSON.parse("null");
returns null. It would be a mistake for invalid JSON to also be parsed to null.
While an empty string is not valid JSON two quotes is valid JSON. This is an important distinction.
Which is to say a string that contains two quotes is not the same thing as an empty string.
JSON.parse('""');
will parse correctly, (returning an empty string). But
JSON.parse('');
will not.
Valid minimal JSON strings are
The empty object '{}'
The empty array '[]'
The string that is empty '""'
A number e.g. '123.4'
The boolean value true 'true'
The boolean value false 'false'
The null value 'null'
Use try-catch to avoid it:
var result = null;
try {
// if jQuery
result = $.parseJSON(JSONstring);
// if plain js
result = JSON.parse(JSONstring);
}
catch(e) {
// forget about it :)
}
What do you choose? Getting lots of conflicting answers.
-
Null
-
Undefined (Omitted from JSON)
-
Empty of that type?
-
String = ""
-
Number = 0
-
Boolean = false
-
Array = []
-
Object = {}
-
CMS JSON API to be consumed by JS Framework Frontend
web api - Use empty string, null or remove empty property in API request/response - Software Engineering Stack Exchange
JSON empty string - Stack Overflow
cjson - What is the JSON Standard for an empty string or null variable? - Stack Overflow
What is the convention in JSON for empty vs. null?
TLDR; Remove null properties
The first thing to bear in mind is that applications at their edges are not object-oriented (nor functional if programming in that paradigm). The JSON that you receive is not an object and should not be treated as such. It's just structured data which may (or may not) convert into an object. In general, no incoming JSON should be trusted as a business object until it is validated as such. Just the fact that it deserialized does not make it valid. Since JSON also has limited primitives compared to back-end languages, it is often worth it to make a JSON-aligned DTO for the incoming data. Then use the DTO to construct a business object (or error trying) for running the API operation.
When you look at JSON as just a transmission format, it makes more sense to omit properties that are not set. It's less to send across the wire. If your back-end language does not use nulls by default, you could probably configure your deserializer to give an error. For example, my common setup for Newtonsoft.Json translates null/missing properties to/from F# option types only and will otherwise error. This gives a natural representation of which fields are optional (those with option type).
As always, generalizations only get you so far. There are probably cases where a default or null property fits better. But the key is not to look at data structures at the edge of your system as business objects. Business objects should carry business guarantees (e.g. name at least 3 characters) when successfully created. But data structures pulled off the wire have no real guarantees.
Going with an empty string is a definitive no. Empty string still is a value, it is just empty. No value should be indicated using a construct which represents nothing, null.
From API developer's point of view, there exist only two types of properties:
- required (these MUST have a value of their specific type and MUST NOT ever be empty),
- optional (these MAY contain a value of their specific type but MAY also contain
null.
This makes it quite clear that when a property is mandatory, ie. required, it can never be null.
On the other hand, should an optional property of an object not be set and left empty, I prefer to keep them in the response anyway with the null value. From my experience it makes it easier for the API clients to implement parsing, as they're not required to check whether a property actually exists or not, because it's always there, and they can simply convert the response to their custom DTO, treating null values as optional.
Dynamically including/removing fields from the response forces including additional conditions on the clients.
Either way, whichever way you choose, make sure you keep it consistent and well documented. That way it really does not matter what you use for your API, as long as the behaviour is predictable.
Old question - but its the top result when you search for 'json stringify empty string' so I'll share the answer I found.
This appears to be a bug in certain versions of IE8, where empty DOM elements return a value which looks like an empty string, evaluates true when compared to an empty string, but actually has some different encoding denoting that it is a null value.
One solution is to do a replace whenever you call stringify.
JSON.stringify(foo, function(key, value) { return value === "" ? "" : value });
See also http://blogs.msdn.com/b/jscript/archive/2009/06/23/serializing-the-value-of-empty-dom-elements-using-native-json-in-ie8.aspx
now the esiest solution for this problem is, to pack the "document.getElementById('id').value" expression in the constructor of the String class:
JSON.stringify({a:new String(document.getElementById('id').value)}); -> {"a":""}
i can't find the primary problem, but with this, it's working well in Internet Explorer as well in FireFox.
i'm not very happy with this dirty solution, but the effort is not to much.
JSON library: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
It should be pretty straight forward.
{
"Value1": null,
"Value2": null,
}
Null represents a null-able datatype so your business layer needs then to know if that is an int, double, string ...
It is entirely up to you.
The falsy values in JavaScript are:
falsenullundefined0NaN''or""
You can use any of these to represent an empty value. However, keep in mind that when you try to access an object's property which doesn't exist, you will get undefined. So undefined can be considered the standard null value, in a way.
Having said that, one convention is to use null so that you can distinguish a property that has been intentionally set to null from a property that is actually undefined.
It is good programming practice to return an empty array [] if the expected return type is an array. This makes sure that the receiver of the json can treat the value as an array immediately without having to first check for null. It's the same way with empty objects using open-closed braces {}.
Strings, Booleans and integers do not have an 'empty' form, so there it is okay to use null values.
This is also addressed in Joshua Blochs excellent book "Effective Java". There he describes some very good generic programming practices (often applicable to other programming langages as well). Returning empty collections instead of nulls is one of them.
Here's a link to that part of his book:
http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html
"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."
Here is my source.