darkmarmot
How to encode JSON with non-string numeric precision?
The international standard for medical messages is currently moving to FHIR: Index - FHIR v5.0.0
They’ve made certain… poor choices (like not including the version id in any message documents).
One of these is that if a message is delivered in JSON format, floats must be encoded as numbers in the JSON with precision preserved. So, for encoding, I can’t use “5.00” with something like Jason. And I can’t use 5.00 because Elixir (and even Javascript) would immediately throw out the zeros.
It would be nice if Elixir had a ‘decimal’ data type for storing precision in a float.
Currently, I’m thinking of forking the Jason library to treat two-tuples as {float_num, precision} (maybe I could sneak a protocol in…) when encoding.
But I’d rather not fork it ![]()
Any other thoughts or ideas to deal with this?
Thanks,
Scott S.
Most Liked
darkmarmot
And solved with a protocol that uses a FHIR.Decimal struct wrapping Decimal ![]()
kip
I’m curious but confused. How could:
floats must be encoded as numbers in the JSON with precision preserved .
even make sense since floats don’t have explicit precision? For example:
iex(5)> << x :: bitstring >> = << 5.0 :: float >>
<<64, 20, 0, 0, 0, 0, 0, 0>>
iex(6)> << x :: bitstring >> = << 5.00000000000000 :: float >>
<<64, 20, 0, 0, 0, 0, 0, 0>>
Different requested precision, exactly the same IEEE encoding. Even @michalmuskala in the cited issue remarks:
This encoding is intentional. The
Decimaldata type is about exact representation of a decimal number - something that cannot be done by a JSON number type, because they are not exact. Encoding decimals as floats would be incorrect and prone to extremely subtle errors - for exampleDecimal.new("9007199254740993.0")if encoded as a straight up JSON number, would be decoded in JavaScript (and most languages) incorrectly as9007199254740992.0since9007199254740993is not representable by a float.
Just curious how this standard requirement (floats preserving precision) could ever actually work!
darkmarmot
It’s a terrible hack idea brought to us by an international standards body that made incompatible versions of a standard without including a version number and no simple way to derive such a thing.
OvermindDL1
This is horrifying… ^.^;
Why don’t they just use ASN.1 or so, it’s well known, stable, efficient, easily versioned, etc… And it’s already used in the medical industry (as I deal with it and use it in the medical industry)…
OvermindDL1
This is already possible and also well typed in ASN.1!
It’s starting to feel like they are trying to convert an ASN.1 schema into json, very poorly, because they don’t match… >.>
Well, if you have to deal with it then forking Jason into a library for it (or maybe PR’ing into Jason in a way that does not change performance for the usual path) would be welcome for others? A dedicated FHIR library perhaps?







