Skip to content

How to omit items that have default values? #84

Open
@iffy

Description

@iffy

I have a situation where JSON strings omit default values. For instance in the code below, if interval is omitted or less than 0, it should be set to 100. What can I do with dumpHook/skipHook to omit default values when I serialize my objects?

import jsony, std/json, std/unittest

type
  Thing = object
    name*: string
    interval*: int

proc newHook*(x: var Thing) =
  if x.interval == 0:
    x.interval = 100

test "defaultvalue":
  let original = """{"name":"bob"}"""
  let thing = original.fromJson(Thing)
  check thing.interval == 100
  let serialized = thing.toJson()
  check parseJson(serialized) == parseJson(original)

test "specificvalue":
  let original = """{"name":"bob", "interval": 200}"""
  let thing = original.fromJson(Thing)
  check thing.interval == 200
  let serialized = thing.toJson()
  check parseJson(serialized) == parseJson(original)

The output of the above is:

parseJson(serialized) was {"name":"bob","interval":100}
parseJson(original) was {"name":"bob"}
[FAILED] defaultvalue
[OK] specificvalue

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