JSON无法正确转换长数字 [英] JSON Not converting long numbers appropriately
问题描述
我有一个简单的JSON,其中无法正确解析数字.
I have a simple JSON where number is not getting parsed properly.
[
{
"orderNumber": 1,
"customerId": 228930314431312345,
"shoppingCartId": 22893031443137109,
"firstName": "jjj"
}
]
我尝试过@ http://www.utilities-online.info/xmltojson/结果是
<?xml version="1.0" encoding="UTF-8" ?>
<orderNumber>1</orderNumber>
<customerId>228930314431312350</customerId>
<shoppingCartId>22893031443137108</shoppingCartId>
<firstName>jjj</firstName>
如您所见....XML与JSON不同.我是JSON的新手.我想念什么吗?
As you can see....the XML is different from JSON. I'm new to JSON. Am I missing something?
推荐答案
这是Javascript精度问题.
This is a Javascript precision problem.
根据Mozilla开发人员网络:
According to Mozilla Developer Network:
ECMA-262仅需要高达21位有效数字的精度.其他实现可能不支持高于标准要求的精度.
ECMA-262 only requires a precision of up to 21 significant digits. Other implementations may not support precisions higher than required by the standard.
来源: https://developer.mozilla.org/zh-CN /docs/JavaScript/Reference/Global_Objects/Number/toPrecision
我将您的数组粘贴到Google Chrome的Javascript控制台中,并返回了以下内容:
I pasted your array into Google Chrome's Javascript console and got back this:
因此,看起来Javascript在将值转换为XML之前对其进行了四舍五入.由于您的转换是通过Javascript在浏览器中完成的,该浏览器位于 http://www.utilities-online.info/xmltojson/,为什么更改号码是有道理的.
So it looks like Javascript is rounding the values before they are being converted to XML. Since your conversion is being done via Javascript in the browser at http://www.utilities-online.info/xmltojson/, it makes sense why the number was changed.
(注意:我使用Windows 7 Professional在Google Chrome版本26.0.1410.43 m上进行了测试)
(Note: I tested on Google Chrome version 26.0.1410.43 m using Windows 7 Professional)
您是否有任何原因无法将这些值作为字符串传递给Javascript?
Is there any reason why you cannot pass these values to Javascript as strings?
尝试一下:
[
{
"orderNumber": "1",
"customerId": "228930314431312345",
"shoppingCartId": "22893031443137109",
"firstName": "jjj"
}
]
我能够执行此操作,并成功保存了值.但是,除非您正在做类似乘以0的操作,否则您将无法在Javascript中对其进行数学计算而不会损失一些精度.
I was able to do this and save the values successfully. However, you will not be able to run a math calculation on them in Javascript without losing some precision, unless you are doing something like multiplying by 0, of course.
这也可以使用您的参考 http://www.utilities-online.info/xmltojson/.
This also converted to XML correctly using your reference http://www.utilities-online.info/xmltojson/.
这篇关于JSON无法正确转换长数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!