且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将JSON中的大数字解析为字符串

更新时间:2023-01-17 14:11:56

免责声明:

这是一个古老的答案,这个问题甚至更老了.您不应该 永远 使用正则表达式解析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