If you do this...
var parsed = JSON.parse('{"myNum":0.0}') ;
Then when you look at parsed.myNum
, you just get 0
. (Fair enough.)
If you do parsed.myNum.toString()
, you get "0"
.
Basically, I'm looking for a way to turn this into the string "0.0"
.
Obviously, in real life I don't control the JSON input, I get the JSON from a web service... I want to parse the JSON using the browser's JSON parser, and to be able to recognise the difference between the number values 0
and 0.0
.
Is there any way to do this, short of manually reading the JSON string? That's not really possible in this case, I need to use the browser's native JSON parser, for speed. (This is for a Chrome extension by the way; no need to worry about it working in other browsers.)
JSON does not have distinct types for integers and floating-point values. Therefore, the presence or absence of a decimal point is not enough to distinguish between integers and non-integers. For example, 1 and 1.0 are two ways to represent the same value in JSON.
The built-in functions (JSON. parse()) are not vulnerable so you can use them safely. However, custom deserialization packages for JavaScript have different types of vulnerabilities, depending on the approach used to deserialize data.
JsonParsingException is used when an incorrect JSON is being parsed.
Parsing JSON is much more efficient than parsing object literals in JavaScript. This is true across all major JavaScript execution engines by up to 2x for an 8MB file, as demonstrated by this parsing benchmark.
If 0.0 is not enclosed in quotes in your JSON (i.e. it's a number and not a string), then there's no way to distinguish it from 0, unless you write your own JSON parser.
There's no way to get the number of digits from JSON.parse
or eval
. Even if IBM's decimal proposal had been adopted by the EcmaScript committee, the number is still going to be parsed to an IEEE 754 float.
Take a look a http://code.google.com/p/json-sans-eval/source/browse/trunk/src/json_sans_eval.js for a simple JSON parser that you can modify to keep precision info.
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