-
Notifications
You must be signed in to change notification settings - Fork 146
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Parse a de facto integer JSON number as an Int #1049
Comments
@seakayone How about |
I would argue, that any integer number in any valid JSON number notation should be converted to an |
I think we should start from understanding the use case. Which problem are we going to solve in general? Is it integration with some other system that has that strange kind of formatting for integers? Should parser on our side report an error or just round silently in case of some fraction part detected? Could accepted values be limited for some range of mantissa and exponent values? |
I am currently migrating from spray to zio-json and noticed the difference in the behaviour. My observation came from a "system that has that strange kind of formatting for integers" reporting an image's
I am under the impression that the more lenient approach when consuming the JSON number would be helpful in cases like above as fringe as they may be. Scala knows that
IMHO if the JSON number is not an integer in the mathematical sense and it does not fit into an
Not really? E.g. To be honest, I understand my case is an edge case and casting JSON integer numbers representations which are technically not an |
@seakayone For your case the following decoder should work if pasted in the scope of codec generation for classes with those implicit val d: JsonDecoder[Int] = (trace: List[JsonError], in: RetractReader) => {
val x = Lexer.double(trace, in)
val y = x.toInt
if (y.toDouble == x) y
else throw UnsafeJson(JsonError.Message("32-bit int expected") :: trace)
} |
@plokhotnyuk thank you very much. I appreciate your effort to help solve my imminent problem. I will actually use a slightly adapted approach to your solution as I am uncomfortable using the implicit val anyWholeNumber: JsonDecoder[Int] = JsonDecoder[Double].mapOrFail { d =>
val i = d.toInt
if (d == i.toDouble) { Right(i) }
else { Left("32-bit int expected") }
} |
Current a valid JSON number like
42.0
(with only zeroes after the decimal point) cannot be parsed as anInt
with zio-json.I would like to argue that zio-json could more lenient and allow for such de facto integer numbers. At least this is the way how spray json used to handle this.
An example test suite (test 3. currently fails and IMHO could pass as well):
The text was updated successfully, but these errors were encountered: