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 test to see if the properties for which there might be a null are indeed null or not before working with them; like this:
if (TheObject.TheProp && TheObject.TheProp.length) {...}
It doesn't crash and it works. My question is this: should I, on the server, populate every property with something (ie. "" for strings and 0 for numbers) because it's considered good practice or is it ok to have null properties on the page?
Thanks for your suggestions.
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 test to see if the properties for which there might be a null are indeed null or not before working with them; like this:
if (TheObject.TheProp && TheObject.TheProp.length) {...}
It doesn't crash and it works. My question is this: should I, on the server, populate every property with something (ie. "" for strings and 0 for numbers) because it's considered good practice or is it ok to have null properties on the page?
Thanks for your suggestions.
Share Improve this question asked Mar 17, 2012 at 16:19 frenchiefrenchie 52.1k117 gold badges320 silver badges528 bronze badges 2-
1
If a property is
null
then it's most semantical to keep itnull
. JSON has anull
value after all; I don't see what advantage an empty string has. – pimvdb Commented Mar 17, 2012 at 16:20 -
Well
""
is two characters shorter thannull
, but in my opinion there's a significant semantic difference between an empty string andnull
; at least, there certainly can be. – Pointy Commented Mar 17, 2012 at 16:20
2 Answers
Reset to default 1In JavaScript null
is a value just like ""
and 0
. A value is undefined
if you have defined it, but not assigned a value, but even that is fine. undefined
will never occur in a JSON data structure though.
Just make sure you handle the null
s correctly and you should be fine.
It's really up to you. If there's a difference between an empty value ""
and an non-existent value null
, then you would want to preserve null
as the marker for the non-existent value and ""
as the market for an empty value.
If there's no difference in your app between the two, then you can indicate an empty string value with either ""
or null
. In some cases, it's' simpler to use ""
because it is a string so you can then treat all your values as strings, but which you use is purely up to your own coding convenience.
There is no single answer which is more right.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745172056a4614986.html
评论列表(0条)