Can there be quotes around JSON numbers? In most of the search links, it seems that numbers do not "require" quotes. But, should the parsers accept both "attr" : 6
and "attr" : "6"
?
If MyParser
has a method getInt
to get a number given the key, should MyParser.getInt("attr")
return 6
in both cases, or throw an exception in the latter case?
JSON numbers follow JavaScript's double-precision floating-point format. Represented in base 10 with no superfluous leading zeros (e.g. 67, 1, 100). Include digits between 0 and 9. Can be a negative number (e.g. -10 .
There are two numeric types in JSON Schema: integer and number. They share the same validation keywords. JSON has no standard way to represent complex numbers, so there is no way to test for them in JSON Schema.
Strings in JSON are specified using double quotes, i.e., " . If the strings are enclosed using single quotes, then the JSON is an invalid JSON .
In JSON, 6
is the number six. "6"
is a string containing the digit 6
. So the answer to the question "Can json numbers be quoted?" is basically "no," because if you put them in quotes, they're not numbers anymore.
But, should the parsers accept both
"attr" : 6
and"attr" : "6"
?
Yes, but they define different things. The first defines an attr
property with the value 6
(a number). The second defines an attr
property with the value "6"
(a string containing a single digit).
(The question originally asked about attr: "6"
, which is invalid because property names must be in double quotes in JSON.)
If MyParser has a method getInt to get a number given the key, should MyParser.getInt("attr") return 6 in both the cases or throw an exception in the latter case?
That's a design decision for the person providing the parser, basically the choice between getInt
being strict (throwing an exception if you try it on "attr": "6"
) or loose (coercing "6"
to 6
and returning that). JavaScript is usually loose, and so there could be an argument for being loose; conversely, the fact that JavaScript is loose sometimes causes trouble, which could be an argument for being strict.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With