Json and null values

On the server I serialize my objects and sometimes some properties are null. On the page, when I parse the string, the null properties are deserialized correctly and in my javascript I check if the properties that can be null are actually null or not before working with them; eg:

if (TheObject.TheProp && TheObject.TheProp.length) {...}


It is not a glitch and it works. My question is this: should I, on the server, populate each property with something (ie "" for strings and 0 for numbers) because it is considered good practice, or is it okay to have null properties on the page?

Thanks for your suggestions.


source to share

2 answers

JavaScript null

has a meaning like ""

and 0

. A value undefined

if you've defined it but not assigned a value, but even that's okay. undefined

will never occur in a JSON data structure.

Just make sure you handle it correctly null

and you should be fine.



It really depends on you. If there is a difference between an empty value ""

and a non-existent value null

, then you would like to store the null

non-existent value as a marker and ""

as a market for the empty value.

If there is no application difference between the two, you can specify an empty string value with ""

or null

. In some cases, "is easier to use ""

because it is a string, so you can treat all of your values ​​as strings, but which one you use just depends on your own coding convenience."

There is no more than one correct answer.



All Articles