Skip to content

Instantly share code, notes, and snippets.

@hiteshjasani
Last active April 21, 2020 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiteshjasani/1f8b962fa53e14316d61b73be8f4c7cd to your computer and use it in GitHub Desktop.
Save hiteshjasani/1f8b962fa53e14316d61b73be8f4c7cd to your computer and use it in GitHub Desktop.
Nim variants and json
import json
type
Kind = enum
kFoo, kBar
Baz = object
name: string
case kind: Kind
of kFoo: iAge: int
of kBar: sAge: string
let foo = Baz(name: "Fred", kind: kFoo, iAge: 23)
let bar = Baz(name: "Sally", kind: kBar, sAge: "22")
let sjfoo = $(%*(foo))
let sjbar = $(%*(bar))
let foo2 = parseJson(sjfoo).to(Baz)
let bar2 = parseJson(sjbar).to(Baz)
echo sjfoo, " => ", $foo2
echo sjbar, " => ", $bar2
# Output
# nim 1.0.6
# {"name":"Fred","kind":"kFoo","iAge":23} => (name: "Fred", kind: kFoo, iAge: 0)
# {"name":"Sally","kind":"kBar","sAge":"22"} => (name: "Sally", kind: kBar, sAge: "")
# nim 1.2.0
# {"name":"Fred","kind":"kFoo","iAge":23} => (name: "Fred", kind: kFoo, iAge: 23)
# {"name":"Sally","kind":"kBar","sAge":"22"} => (name: "Sally", kind: kBar, sAge: "22")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment