3 ms·
> whatever string you use to represent the null value EG > "null" is now a keyword that needs to be enforced. So in the JSON itself, you literally remove the
by bArray 6y ago
> whatever string you use to represent the null value EG
> "null" is now a keyword that needs to be enforced.
So in the JSON itself, you literally remove the field. In another comment I make is the point that NULL itself could be considered a proper value, you're just pushing the problem down the line. The library making such a decision for you is what may ultimately trip you up.
Instead, you could have something like:
string name = jobj.get("name", NULL)
So that it does return NULL in this case if a name hasn't been given.
But consider an example where you're loading some code into a VM's RAM:
int location = toint(jobj.get("address"))
NULL in this case is a perfectly valid place to load a program in a VM, or was it that there was an error? Or is it that no address was given in the JSON configuration?
Instead, we can specify our own "NULL" value:
int location = toint(jobj.get("address", "-1"))
So now you're asking to load something before the first position of the VM memory, which indicates an error.
- gitgud 6y agoI think we're in agreement, originally it was suggested to use a "null" string, instead of NULL as a value, which is what I said might cause weird error cases. > So in the JSON itself, you literally remove the field. That's a good point, but in some cases having a `null` is an easier option, as you only need to determine if the value is valid, not if it exists AND is valid (but I suppose you could say it's always valid if it exists... that's if you trust the endpoint to provide valid values though). > But consider an example where you're loading some code into a VM's RAM Allocating memory locations from dynamically created JSON values is bound to lead to many different errors... I guess my main point is that JSON is inherently untyped and suited for messy data or user input. This messiness makes data validation on the consumer of the JSON necessary, which means the consumer has to check if the value is valid before using it. In most cases `null` is considered invalid but if the field isn't there, then it could be an error in the JSON provider.