json.lua icon indicating copy to clipboard operation
json.lua copied to clipboard

Large numbers lose precision when decoding

Open NewPProd opened this issue 5 years ago • 2 comments

A web service I need to use is returning the following in its JSON: "Id":1618065507111835497

But when using this Lua library to decode it, the result is losing precision as "Id" is returned as: 1.6080655071118e+18

In this case I can't change what the webservice is providing. I'm quite happy referring the data as a string - it's just an id value. I am limited to only using Lua 5.1.4.

Any help appreciated (e.g. pass back numbers that can't be correctly converted as strings?).

Thanks, Rob

NewPProd avatar Dec 30 '20 18:12 NewPProd

But when using this Lua library to decode it, the result is losing precision as "Id" is returned as:

Decoding looks ok to me:

Lua 5.3.3  Copyright (C) 1994-2016 Lua.org, PUC-Rio
> json = require 'json'
> d = json.decode('{"id":1618065507111835497}')
> print(d.id)
1618065507111835497

But encoding does lose the precision:

> json.encode({id=1618065507111835497})
{"id":1.6180655071118e+18}

jtackaberry avatar Jan 04 '21 02:01 jtackaberry

I think the problem is that Lua 5.1.4 does not include 64 bit integers, this was added in Lua 5.3. When I try and perform the same decode example on Lua 5.1.4 I lose precision. I'm restricted to using Lua 5.1.4 as it is embedded in the host application.

Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> json = require 'json'
> d = json.decode('{"id":1618065507111835497}')
> print(d.id)
1.6180655071118e+018

NewPProd avatar Jan 04 '21 10:01 NewPProd