Skip to content

Support object variants #22

@planetis-m

Description

@planetis-m

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions