Some values in JSON cannot be represented in JavaScript with full fidelity. For example:
9999999999999999999999999
I am working on a protocol/application that requires interoperability and we use JSON as our data interchange format. In my JavaScript implementation, I would like the JSON parser to throw on those inputs.
I have created a simple (and wrong) function to do this.
function safeDecodeJson(str) {
decoded = JSON.parse(str);
reencoded = JSON.stringify(decoded);
if (str != reencoded) {
throw new RangeError();
}
return decoded;
}
Here is a test case:
jsonString = "9999999999999999999999999";
safeDecodeJson(jsonString);
It does throw the RangError.
My issue is that this safeDecodeJson function only works if the input is minimal. Is there a more robust way to implement this function?
To be super specific, I am concerned about a "non-injective attack" on the input JSON file. My system requires that logically-distinct JSON inputs (like 9999999999999999999999999 and 9999999999999999999999998) have distinct representations in JavaScript. Or the function must throw.