Unreal user Unreal user - 4 months ago 23
JSON Question

Can Json numbers be quoted?

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 the cases or throw an exception in the latter case?

Answer

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"?

The second example is invalid, because attr must be in quotes, e.g.:

{"attr": "6"}

...is valid, and defines an object with a property called attr with the string value "6", whereas:

{"attr": 6}

...is valid, and defines an object with a property called attr with the number value 6, and finally:

{attr: 6}

...and

{attr: "6"}

...are both invalid JSON because property names must be in double quotes.

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" into 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.

Comments