Re: Default value for missing JSON fields

2019-01-02 Thread jegfish
Could you (or anyone else) please provide guidance as to what I could do to 
preserve an easy to use interface for users of my library?

Currently I have 2 ideas.

  * The first is to define types with the appropriate private fields for the 
JSON and defining exported getter procedures for people importing the module.
  * The other is to define custom procedures for converting the JSON to Nim 
objects.



Currently I am leaning towards the second because I think truly accessing 
fields feels better than replacing them with procedures, but I am not 
experienced enough in Nim or programming in general to know if there may be 
harmful effects of either possibility, or if there may be other options.


Re: Default value for missing JSON fields

2019-01-01 Thread dom96
Sadly you have to use an `Option` in this case. I'm afraid the to macro doesn't 
support anything else.


Default value for missing JSON fields

2018-12-31 Thread jegfish
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.