Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent removing decimal point when parsing JSON?

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.)

like image 278
callum Avatar asked Apr 02 '11 01:04

callum


People also ask

Can JSON store decimal values?

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.

Is JSON parse insecure?

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.

What is JSON parsing exception?

JsonParsingException is used when an incorrect JSON is being parsed.

How efficient is JSON parse?

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.


2 Answers

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.

like image 179
awm Avatar answered Oct 16 '22 19:10

awm


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.

like image 35
Mike Samuel Avatar answered Oct 16 '22 19:10

Mike Samuel