Skip to content

Commit

Permalink
Add possibility to parse JSON to set and option
Browse files Browse the repository at this point in the history
* Use `jsonutils.nim` hookable API to add possibility to deserialize
  JSON arrays directly to `HashSet` and `OrderedSet` types and
  respectively to serialize those types to JSON arrays.

* Also add possibility to deserialize JSON `null` objects to Nim option
  objects and respectively to serialize Nim option object to JSON object
  if some or to JSON `null` object if none.

* Move serialization/deserialization functionality for `Table` and
  `OrderedTable` types from `jsonutils.nim` to `tables.nim` via the
  hookable API.

* Add object `jsonutils.Joptions` and parameter from its type to
  `jsonutils.fromJson` procedure to control whether to allow
  deserializeing JSON objects to Nim objects when the JSON has some
  extra or missing keys.

* Add unit tests for the added functionalities to `tjsonutils.nim`.
  • Loading branch information
bobeff committed Aug 4, 2020
1 parent d130175 commit cca3ba7
Show file tree
Hide file tree
Showing 5 changed files with 333 additions and 34 deletions.
38 changes: 37 additions & 1 deletion lib/pure/collections/sets.nim
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ type
## <#initOrderedSet,int>`_ before calling other procs on it.
data: OrderedKeyValuePairSeq[A]
counter, first, last: int
SomeSet*[A] = HashSet[A] | OrderedSet[A]
## Type union representing `HashSet` or `OrderedSet`.

const
defaultInitialSize* = 64
Expand Down Expand Up @@ -907,7 +909,41 @@ iterator pairs*[A](s: OrderedSet[A]): tuple[a: int, b: A] =
forAllOrderedPairs:
yield (idx, s.data[h].key)


proc fromJsonHook*[A, B](s: var SomeSet[A], jsonNode: B) =
## Enables `fromJson` for `HashSet` and `OrderedSet` types.
##
## See also:
## * `toJsonHook proc<#toJsonHook,SomeSet[A]>`_
runnableExamples:
import std/[json, jsonutils]
var foo: tuple[hs: HashSet[string], os: OrderedSet[string]]
fromJson(foo, parseJson("""
{"hs": ["hash", "set"], "os": ["ordered", "set"]}"""))
assert foo.hs == ["hash", "set"].toHashSet
assert foo.os == ["ordered", "set"].toOrderedSet

mixin jsonTo
assert jsonNode.kind == JArray,
"The kind of the `jsonNode` must be `JArray`, but its actual " &
"type is `" & $jsonNode.kind & "`."
clear(s)
for v in jsonNode:
incl(s, jsonTo(v, A))

proc toJsonHook*[A](s: SomeSet[A]): auto =
## Enables `toJson` for `HashSet` and `OrderedSet` types.
##
## See also:
## * `fromJsonHook proc<#fromJsonHook,SomeSet[A],B>`_
runnableExamples:
import std/[json, jsonutils]
let foo = (hs: ["hash"].toHashSet, os: ["ordered", "set"].toOrderedSet)
assert $toJson(foo) == """{"hs":["hash"],"os":["ordered","set"]}"""

mixin newJArray, toJson
result = newJArray()
for k in s:
add(result, toJson(k))

# -----------------------------------------------------------------------

Expand Down
41 changes: 38 additions & 3 deletions lib/pure/collections/tables.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1750,9 +1750,44 @@ iterator mvalues*[A, B](t: var OrderedTable[A, B]): var B =
yield t.data[h].val
assert(len(t) == L, "the length of the table changed while iterating over it")




proc fromJsonHook*[K, V, JN](t: var (Table[K, V] | OrderedTable[K, V]),
jsonNode: JN) =
## Enables `fromJson` for `Table` and `OrderedTable` types.
##
## See also:
## * `toJsonHook proc<#toJsonHook,(Table[K,V]|OrderedTable[K,V])>`_
runnableExamples:
import std/[json, jsonutils]
var foo: tuple[t: Table[string, int], ot: OrderedTable[string, int]]
fromJson(foo, parseJson("""
{"t":{"two":2,"one":1},"ot":{"one":1,"three":3}}"""))
assert foo.t == [("one", 1), ("two", 2)].toTable
assert foo.ot == [("one", 1), ("three", 3)].toOrderedTable

mixin jsonTo
assert jsonNode.kind == JObject,
"The kind of the `jsonNode` must be `JObject`, but its actual " &
"type is `" & $jsonNode.kind & "`."
clear(t)
for k, v in jsonNode:
t[k] = jsonTo(v, V)

proc toJsonHook*[K, V](t: (Table[K, V] | OrderedTable[K, V])): auto =
## Enables `toJson` for `Table` and `OrderedTable` types.
##
## See also:
## * `fromJsonHook proc<#fromJsonHook,(Table[K,V]|OrderedTable[K,V]),JN>`_
runnableExamples:
import std/[json, jsonutils]
let foo = (
t: [("two", 2)].toTable,
ot: [("one", 1), ("three", 3)].toOrderedTable)
assert $toJson(foo) == """{"t":{"two":2},"ot":{"one":1,"three":3}}"""

mixin newJObject, toJson
result = newJObject()
for k, v in pairs(t):
result[k] = toJson(v)

# ---------------------------------------------------------------------------
# --------------------------- OrderedTableRef -------------------------------
Expand Down
36 changes: 36 additions & 0 deletions lib/pure/options.nim
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,42 @@ proc unsafeGet*[T](self: Option[T]): T {.inline.}=
assert self.isSome
self.val

proc fromJsonHook*[T, JN](self: var Option[T], jsonNode: JN) =
## Enables `fromJson` for `Option` types.
##
## See also:
## * `toJsonHook proc<#toJsonHook,Option[T]>`_
runnableExamples:
import std/[json, jsonutils]
var opt: Option[string]
fromJsonHook(opt, parseJson("\"test\""))
assert get(opt) == "test"
fromJson(opt, parseJson("null"))
assert isNone(opt)

mixin jsonTo, JNull
if jsonNode.kind != JNull:
self = some(jsonTo(jsonNode, T))
else:
self = none[T]()

proc toJsonHook*[T](self: Option[T]): auto =
## Enables `toJson` for `Option` types.
##
## See also:
## * `fromJsonHook proc<#fromJsonHook,Option[T],JN>`_
runnableExamples:
import std/[json, jsonutils]
let optSome = some("test")
assert $toJson(optSome) == "\"test\""
let optNone = none[string]()
assert $toJson(optNone) == "null"

mixin toJson, newJNull
if isSome(self):
toJson(get(self))
else:
newJNull()

when isMainModule:
import unittest, sequtils
Expand Down
105 changes: 76 additions & 29 deletions lib/std/jsonutils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,11 @@ runnableExamples:
let j = a.toJson
doAssert j.jsonTo(type(a)).toJson == j

import std/[json,tables,strutils]
import std/[json,strutils]

#[
xxx
use toJsonHook,fromJsonHook for Table|OrderedTable
add Options support also using toJsonHook,fromJsonHook and remove `json=>options` dependency
Future directions:
add a way to customize serialization, for eg:
* allowing missing or extra fields in JsonNode
* field renaming
* allow serializing `enum` and `char` as `string` instead of `int`
(enum is more compact/efficient, and robust to enum renamings, but string
Expand All @@ -32,6 +27,17 @@ add a way to customize serialization, for eg:

import std/macros

type
Joptions* = object
## Options controlling the behavior of `fromJson`.
allowExtraKeys*: bool
## If `true` Nim's object to which the JSON is parsed is not required to
## have a field for every JSON key.
allowMissingKeys*: bool
## If `true` Nim's object to which JSON is parsed is allowed to have
## fields without corresponding JSON keys.
# in future work: a key rename could be added

proc isNamedTuple(T: typedesc): bool {.magic: "TypeTrait".}
proc distinctBase(T: typedesc): typedesc {.magic: "TypeTrait".}
template distinctBase[T](a: T): untyped = distinctBase(type(a))(a)
Expand All @@ -58,11 +64,11 @@ macro getDiscriminants(a: typedesc): seq[string] =
result = quote do:
seq[string].default

macro initCaseObject(a: typedesc, fun: untyped): untyped =
macro initCaseObject(T: typedesc, fun: untyped): untyped =
## does the minimum to construct a valid case object, only initializing
## the discriminant fields; see also `getDiscriminants`
# maybe candidate for std/typetraits
var a = a.getTypeImpl
var a = T.getTypeImpl
doAssert a.kind == nnkBracketExpr
let sym = a[1]
let t = sym.getTypeImpl
Expand Down Expand Up @@ -92,31 +98,59 @@ proc checkJsonImpl(cond: bool, condStr: string, msg = "") =
template checkJson(cond: untyped, msg = "") =
checkJsonImpl(cond, astToStr(cond), msg)

template fromJsonFields(a, b, T, keys) =
checkJson b.kind == JObject, $(b.kind) # we could customize whether to allow JNull
proc hasField[T](obj: T, field: string): bool =
for k, _ in fieldPairs(obj):
if k == field:
return true
return false

macro accessField(obj: typed, name: static string): untyped =
newDotExpr(obj, ident(name))

template fromJsonFields(newObj, oldObj, json, discKeys, numMatched, opt) =
type T = typeOf(newObj)
# we could customize whether to allow JNull
checkJson json.kind == JObject, $json.kind
var num = 0
for key, val in fieldPairs(a):
for key, val in fieldPairs(newObj):
num.inc
when key notin keys:
if b.hasKey key:
fromJson(val, b[key])
when key notin discKeys:
if json.hasKey key:
numMatched.inc
fromJson(val, json[key])
elif opt.allowMissingKeys:
# if there is no discriminant keys the `oldObj` must always have the
# same keys and the new one. Otherwise we must check, because the could
# be set to different branches.
if discKeys.len == 0 or hasField(oldObj, key):
val = accessField(oldObj, key)
else:
# we could customize to allow this
checkJson false, $($T, key, b)
checkJson b.len == num, $(b.len, num, $T, b) # could customize
checkJson false, $($T, key, json)

proc fromJson*[T](a: var T, b: JsonNode) =
let ok =
if opt.allowExtraKeys and opt.allowMissingKeys:
true
elif opt.allowExtraKeys:
# This check is redundant because if here missing keys are not allowed,
# and if `num != numMatched` it will fail in the loop above but it is left
# for clarity.
assert num == numMatched
num == numMatched
elif opt.allowMissingKeys:
json.len == numMatched
else:
json.len == num and num == numMatched

checkJson ok, $(json.len, num, numMatched, $T, json)

proc fromJson*[T](a: var T, b: JsonNode, opt = Joptions()) =
## inplace version of `jsonTo`
#[
adding "json path" leading to `b` can be added in future work.
]#
checkJson b != nil, $($T, b)
when compiles(fromJsonHook(a, b)): fromJsonHook(a, b)
elif T is bool: a = to(b,T)
elif T is Table | OrderedTable:
a.clear
for k,v in b:
a[k] = jsonTo(v, typeof(a[k]))
elif T is enum:
case b.kind
of JInt: a = T(b.getBiggestInt())
Expand Down Expand Up @@ -148,14 +182,30 @@ proc fromJson*[T](a: var T, b: JsonNode) =
for i, val in b.getElems:
fromJson(a[i], val)
elif T is object:
var numMatched = 0
template fun(key, typ): untyped =
jsonTo(b[key], typ)
a = initCaseObject(T, fun)
if b.hasKey key:
numMatched.inc
jsonTo(b[key], typ)
elif hasField(a, key):
accessField(a, key)
else:
default(typ)
const keys = getDiscriminants(T)
fromJsonFields(a, b, T, keys)
when keys.len > 0:
var newObj = initCaseObject(T, fun)
fromJsonFields(newObj, a, b, keys, numMatched, opt)
a = newObj
else:
var newObj: T
fromJsonFields(newObj, a, b, seq[string].default, numMatched, opt)
a = newObj
elif T is tuple:
when isNamedTuple(T):
fromJsonFields(a, b, T, seq[string].default)
var numMatched = 0
var newObj: T
fromJsonFields(newObj, a, b, seq[string].default, numMatched, opt)
a = newObj
else:
checkJson b.kind == JArray, $(b.kind) # we could customize whether to allow JNull
var i = 0
Expand All @@ -175,9 +225,6 @@ proc toJson*[T](a: T): JsonNode =
## serializes `a` to json; uses `toJsonHook(a: T)` if it's in scope to
## customize serialization, see strtabs.toJsonHook for an example.
when compiles(toJsonHook(a)): result = toJsonHook(a)
elif T is Table | OrderedTable:
result = newJObject()
for k, v in pairs(a): result[k] = toJson(v)
elif T is object | tuple:
when T is object or isNamedTuple(T):
result = newJObject()
Expand Down
Loading

0 comments on commit cca3ba7

Please sign in to comment.