Reputation: 18248
Given a JSON such:
[
{ "id":"A", "status": 1, "rank":1, "score": },
{ "id":"B", "status": 1, "rank":1, "score": }
]
My script fails due to the empty score.
Given a JS such :
if (json[i].score) { do something } else { calculate it }
I want to keep the field empty, and not use 0. I may use "score": ""
, but this will imply that it's a string (empty at start), while I want score to be a numeral (empty at start). So the number I push in it stay a number, and not a string.
How to state an empty/undefined numeral ?
Note: I intuitively think it's why I sometime meet undefined
.
EDIT: the question was edited to clarify the context, the need to check the existence of obj.score, where 0 would be misleading.
Upvotes: 2
Views: 8361
Reputation: 137320
TL;DR: Use 0
(zero), if everyone starts with zero score. Use null
, if you specifically want to say that someone's score is not set yet. Do not define the property, if it should not be placed in specific case (like object that should not even have "score"
property).
Well, in JSON you are not allowed to just omit the value. It must be set to something like number (integer or float), object, list, boolean, null or string. To read more about syntax, try this resource: http://json.org/. This is the diagram taken from that site, showing you the syntax of object representations in JSON:
null
, 0
(zero), undefinedThe usual approach is to set null
. In other cases it can be better to use 0
(zero), if applicable (eg. the field means "sum").
Another approach is just to not set the property. After deserialization you are then able to perform tests checking the existence of specific property like that:
JavaScript:
if (typeof my_object.score !== 'undefined'){
// "score" key exists in the object
}
Python:
if 'score' in my_object:
pass # "score" key exists in the object
PHP:
if (array_key_exists('score', $my_object)) {
// "score" key exists in the object
}
false
, ""
Some people also accept the value to be false
in such case, but it is rather inconsistent. Similarly when it comes to empty string (""
). However, both cases should be properly supported in most programming languages during deserialization.
Upvotes: 5
Reputation: 5620
By definition, a numeral value is a value type, which cannot be null
. Only reference types (like strings, arrays, etc.) should be initialized to null
.
For the semantic of your situation, I would suggest you to use a boolean to know if weither or not there is a score to be read.
[
{ "id":"A", "status": 1, "rank":1, "empty":true },
{ "id":"B", "status": 1, "rank":1, "empty":false, "score":100}
]
Then,
if (!foo.empty) {
var score = foo.score;
}
While a null
could be tested as well, it is a wrong representation of a number.
Upvotes: 1
Reputation: 3716
Why not just start score at 0? Everyone will start with a score of 0 in just about anything involving score.
[
{ "id":"A", "status": 1, "rank":1, "score": 0 },
{ "id":"B", "status": 1, "rank":1, "score": 0 }
]
Upvotes: 1