Hey there,
I'm a Python dev getting into Nim.
As the paradigm is very new to me, I'm wondering how to convert a JSON string into a type.
Here's what I have:
import json
type
Asset = object
percentage: float
let content = """[{"percentage": "0.5"}, {"percentage": "0.9"}]""".parseJson()
to(content, Asset[0])
I get the following error:
Incorrect JSON kind. Wanted '{JInt, JFloat}' in '.percentage' but got 'JString'
I'm aware the JSON is a string and should be a float, but I can't modify it (remove server providing it).
What would be the best practice to map the json to my Asset? Anyway to cast automagically or do I have to convert manually each value before unmarshalling into Asset?
Thanks Nim community! :)
Deserialization usage can be seen in jsony repo: https://github.com/treeform/jsony/blob/35d9fa6/tests/bench.nim#L13-L57
Why so many? Some kind of json frenzy took Nim developers in January. Origin of the pandemic unknown, exercise caution.
Using jsony you can define a parseHook() that optionally checks if the float you want is actually a string:
import jsony, print, strutils
proc parseHook(s: string, i: var int, v: var float) =
## Optionally parse floats strings as real floats.
## Example: "0.9" -> 0.9
eatSpace(s, i)
if s[i] == '"':
var floatStr: string
parseHook(s, i, floatStr)
v = parseFloat(floatStr)
else:
v = parseFloat(parseSymbol(s, i))
type
Asset = object
percentage: float
let content = """[{"percentage": "0.5"}, {"percentage": "0.9"}]"""
let assets = content.fromJson(seq[Asset])
print assets
But if you can change the json that is passed to you, i would just store them as floats to start with with.
Also if you are dealing with a ton of json, jsony is pretty fast, faster than std lib json.
Why so many?
I'd say it could be a sign that STD JSON library is not good and needs improvement.