I am trying to write a wrapper for a JSON API and I want to map its JSON
objects to custom Nim objects. I am having trouble figuring out what to do with
fields that aren't always provided in the JSON objects.
import json
type
Type = object
# Normal field, always in the JSON object
normal: string
# Field that isn't always there, should have a default of false when it
isn't
default: bool
let easy = to(parseJson("""
{
"normal": "some string",
"default": true
}
"""), Type)
let hard = to(parseJson("""
{
"normal": "some string"
}
"""), Type)
doAssert easy.default == true
doAssert hard.default == false
Run
Obviously this code will raise an error for the "hard" variable, but I would
like to find a way around this. I have looked at the [options
module](https://nim-lang.org/docs/options.html), but since I am trying to make
this wrapper easy to use, I don't want my end users to deal with Option types.
If it helps, I believe all of the possibly missing fields in the API end up
defaulting to zero values like false or nil.