planetis-m / jsonpak

Packed ASTs for compact and efficient JSON representation, with JSON Pointer, JSON Patch support.
https://planetis-m.github.io/jsonpak/
MIT License
24 stars 1 forks source link

Support object variants #22

Open planetis-m opened 2 years ago

planetis-m commented 2 years ago

suggested transformation:

type
  Fruit = enum
    Banana, Apple
  Bar = object
    case kind: Fruit
    of Banana:
      bad: float
      banana: int
    of Apple: apple: string

proc initFromJson(dst: var Bar; tree: JsonTree; n: NodePos) =
  verifyJsonKind(tree, n, {JObject})
  var kindTmp: Fruit
  initFromJson(kindTmp, tree, rawGet(tree, n, "kind"))
  dst = (typeof dst)(kind: kindTmp)
  for x in keys(tree, n):
    case dst.kind
    of Banana:
      case x.str
      of "bad":
        initFromJson(dst.bad, tree, x.firstSon)
      of "banana":
        initFromJson(dst.banana, tree, x.firstSon)
      else: discard
    of Apple:
      case x.str
      of "apple":
        initFromJson(dst.apple, tree, x.firstSon)
      else: discard

let x = parseJson("""{"kind":"Apple","apple":"world"}""")
var b: Bar
initFromJson(b, x, rootNodeId)
echo b
planetis-m commented 5 months ago

This is needlessly complicated due to recursive RecList. Let's wait until sum types land.