I am very new to the Nim language. However, in only 2 hours time, I successfully converted an existing project of mine into Nim. Wow! However, now I want to be able to store/restore an object by using a json file.
When I try the code at the nim-by-example json tutorial, it works perfectly.
However, when I try this code (in a separate module):
import std/json
type
Planet* = ref object
name*: string
pos*: tuple[x: float, y: float]
proc `%*`(planet: Planet) : JsonNode =
result = %* {
"name": planet.name,
"pos": [ planet.pos.x, planet.pos.y ]
}
I get this error:
Error: type mismatch: got '(string, array[0..1, float])' for '("pos", [planet.pos.x, planet.pos.y])' but expected '(string, string)'
Why am I getting this error? I don't see the difference with the tutorial where an integer is put into the json data. I changed it to a tuple and it works too.
The issue you're seeing is simply that you reused the %* identifier for your custom JsonNode converter. It confuses the compiler. %* is an untyped macro in the JSON module, which applies % to every field essentially.
So for your own JSON converter procs for a type, you'll want to use % as well. A working example:
import std/json
type
Planet* = ref object
name*: string
pos*: tuple[x: float, y: float]
proc `%`(planet: Planet) : JsonNode =
result = %* {
"name": planet.name,
"pos": [ planet.pos.x, planet.pos.y ]
}
let p = Planet(name: "Earth", pos: (x: 149.6e9, y: 0.0))
echo pretty(% p)