JSON 未正确转换长数字 [英] JSON Not converting long numbers appropriately

查看:28
本文介绍了JSON 未正确转换长数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 JSON,其中没有正确解析数字.

<代码>[{订单号":1,客户 ID":228930314431312345,"shoppingCartId": 22893031443137109,名字":jjj"}]

我试过@,为什么要更改数字是有道理的.

(注意:我使用 Windows 7 Professional 在 Google Chrome 版本 26.0.1410.43 m 上进行了测试)

有什么理由不能将这些值作为字符串传递给 Javascript 吗?

试试这个:

<代码>[{订单号":1","customerId": "228930314431312345","shoppingCartId": "22893031443137109",名字":jjj"}]

我能够做到这一点并成功保存值.但是,您将无法在 Javascript 中对它们进行数学计算而不会损失一些精度,当然,除非您正在执行诸如乘以 0 之类的操作.

这也使用您的参考正确转换为 XML http://www.utilities-online.info/xmltojson/.

I have a simple JSON where number is not getting parsed properly.

[
  {
    "orderNumber": 1,
    "customerId": 228930314431312345,
    "shoppingCartId": 22893031443137109,
    "firstName": "jjj"
  }
]

I tried it @ http://www.utilities-online.info/xmltojson/ and the result was

<?xml version="1.0" encoding="UTF-8" ?>
<orderNumber>1</orderNumber>
<customerId>228930314431312350</customerId>
<shoppingCartId>22893031443137108</shoppingCartId>
<firstName>jjj</firstName>

As you can see....the XML is different from JSON. I'm new to JSON. Am I missing something?

解决方案

This is a Javascript precision problem.

According to Mozilla Developer Network:

ECMA-262 only requires a precision of up to 21 significant digits. Other implementations may not support precisions higher than required by the standard.

Source: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toPrecision

I pasted your array into Google Chrome's Javascript console and got back this:

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.

(Note: I tested on Google Chrome version 26.0.1410.43 m using Windows 7 Professional)

Edit:

Is there any reason why you cannot pass these values to Javascript as strings?

Try this:

[
  {
    "orderNumber": "1",
    "customerId": "228930314431312345",
    "shoppingCartId": "22893031443137109",
    "firstName": "jjj"
  }
]

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.

This also converted to XML correctly using your reference http://www.utilities-online.info/xmltojson/.

这篇关于JSON 未正确转换长数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆