将JSON中的大数字解析为字符串 [英] Parsing big numbers in JSON to strings

查看:235
本文介绍了将JSON中的大数字解析为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JSON.parse()舍入大数来解决该问题.我知道为什么会这样,但我正在寻找解决之道.

I'm trying to tackle the issue with JSON.parse() rounding big numbers. I know why this is happening but am looking for away around it.

我在考虑一个正则表达式,可以解析JSON文本并将所有大整数转换为字符串.

I was thinking a regex which could parse the JSON text and turn all the big ints into strings.

我正在Windows 8应用程序中使用JavaScript,并且必须由客户端处理.

I'm using JavaScript in a Windows 8 app and its got to be dealt with client side.

到目前为止,让我感到难过

Got me stumped so far.

主要问题是,在收到XMLHTTPRequest的响应并且无法更改JSON的原始格式后,我必须这样做

The main issue is I have to do this after I receive the response from an XMLHTTPRequest and cant change the original format of the JSON

例如

{ "data" : {
    "username":"Brad", "userID":941022167561310208, "location":"London"
    }
}

推荐答案

免责声明:

这是一个古老的答案,这个问题甚至更老了.您不应该 永远 使用正则表达式解析JSON-解决方案过于脆弱,容易被随机破坏.正确的方法是解析整个JSON字符串,然后使用代码将字符串值转换为数字,例如parseInt(jsonData.data.userID).

This is an old answer, and the question is even older. You shouldn't ever be parsing JSON with regular expressions - it's too brittle of a solution, and is liable to break at random. The right way to do this is to parse the entire JSON string, then use code to convert string values to numbers, e.g. parseInt(jsonData.data.userID).

一种更好的方法是将其固定在后端,这样客户就不必这样做了.

An even better way to do it is to fix it on your back-end so your client doesn't have to do this.

这是将所有整数都用引号引起来的正则表达式.如果只想对长字符串执行此操作,请将+更改为{9,}(或任何int).

Here's the regex to wrap all integers with quotes. If you wanted to do this only for long strings, change + to {9,} (or any int).

var json = ('{"data":{"username":"Brad","userID":941022167561310208,"location":"London","test":"3908349804","test2":"This already exists in 034093049034 quotes"},"list":[3409823408,3409823408,"A list 234908234"]}');
json = json.replace(/([\[:])?(\d+)([,\}\]])/g, "$1\"$2\"$3");
json = JSON.parse(json);

请参阅示例: http://jsfiddle.net/remus/6YMYT/

编辑也进行了更新,以容纳列表.

Edit Updated to accommodate lists as well.

以下是正在使用的正则表达式: http://regex101.com/r/qJ3mD2

Here's the regex in action: http://regex101.com/r/qJ3mD2

这篇关于将JSON中的大数字解析为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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