简体   繁体   中英

In Javascript ,how to represent 1.00 as a number in a JSON object?

All I want to do is to create a JSON string like this :

'{  "a" : 1.00 }'

I have tried

var n = 1.00;
var x = { a : n };
console.log(JSON.stringify(x)); // Gives {"a":1}

var n = 1.00;
var x = { a : n.toFixed(2) };
console.log(JSON.stringify(x)); // Gives {"a":"1.00"}

var x = { x : 1.00 };    
x = JSON.stringify(x , function(key,val ){
    if( typeof val === "number")
        return val.toFixed(2);

    return val;
});

console.log(x); // Gives {"x":"1.00"}

Is it even possible to represent '{ "a" : 1.00 }' as a JSON string in javascript ? If yes, how can I do it ?

A number in JSON doesn't have any specific precision. A number is represented as the shortest notation that is needed to reproduce it.

The value 1.00 is the same as the value 1 , so that is how it is represented in JSON.

If you specifically want to represent a number in the 1.00 format, then you can't store it as a number, you would need to use a string.

The string '{"x":1.00}' is valid JSON, but it has the same meaning as '{"x":1}' .

toFixed() returns a string, and therefore will always result in "1.00" instead of 1.00.

The only way I can think of to get a JSON string with 1.00 as a value is to create it like you did above with toFixed(), then modify the string afterwards by either removing the quote characters from "1.00".

You could also create it without toFixed() and then go in and add the .00 characters.

Either way it strikes me as more effort than it's worth, but it should be possible. I can't think of a way to do it directly.

What you are trying to achieve is out of the scope of serialized object concept. Serialization is about presenting data in the most general way so both sender and the receiver of this serialized object will be able to understand in any programming language. The definition of this data type you are trying to represent is called 'Number' in JSON. You should parse or cast it to the type you need (this is part of the deserialization concept, and usually being done by the JSON parsing method).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM