Skip to content

Commit

Permalink
Add possibility to parse JSON to set
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.

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

* Add `allowMissingFields` parameter to `jsonutils.fromJson` procedure
  to be able to deserialize JSON objects to Nim objects when some of the
  corresponding fields are missing.
  • Loading branch information
bobeff committed Jul 31, 2020
1 parent d130175 commit fe681f3
Show file tree
Hide file tree
Showing 3 changed files with 106 additions and 21 deletions.
49 changes: 48 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,52 @@ 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]
type
Foo = object
hs: HashSet[string]
os: OrderedSet[string]
var foo: Foo
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]
type
Foo = object
hs: HashSet[string]
os: OrderedSet[string]
let foo = Foo(
hs: ["hash", "set"].toHashSet,
os: ["ordered", "set"].toOrderedSet)
assert $toJson(foo) == """{"hs":["set","hash"],"os":["ordered","set"]}"""

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

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

Expand Down
53 changes: 50 additions & 3 deletions lib/pure/collections/tables.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1750,9 +1750,56 @@ 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")




type
SomeTable*[K, V] = Table[K, V] | OrderedTable[K, V]
## Type union representing `Table` or `OrderedTable`.

proc fromJsonHook*[K, V, JN](t: var SomeTable[K, V], jsonNode: JN) =
## Enables `fromJson` for `Table` and `OrderedTable` types.
##
## See also:
## * `toJsonHook proc<#toJsonHook,SomeTable[K,V]>`_
runnableExamples:
import std/[json, jsonutils]
type
Foo = object
t: Table[string, int]
ot: OrderedTable[string, int]
var foo: Foo
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: SomeTable[K, V]): auto =
## Enables `toJson` for `Table` and `OrderedTable` types.
##
## See also:
## * `fromJsonHook proc<#fromJsonHook,SomeTable[K,V],JN>`_
runnableExamples:
import std/[json, jsonutils]
type
Foo = object
t: Table[string, int]
ot: OrderedTable[string, int]
let foo = Foo(
t: [("one", 1), ("two", 2)].toTable,
ot: [("one", 1), ("three", 3)].toOrderedTable)
assert $toJson(foo) == """{"t":{"two":2,"one":1},"ot":{"one":1,"three":3}}"""

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

# ---------------------------------------------------------------------------
# --------------------------- OrderedTableRef -------------------------------
Expand Down
25 changes: 8 additions & 17 deletions lib/std/jsonutils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,14 @@ 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 Down Expand Up @@ -92,31 +90,27 @@ proc checkJsonImpl(cond: bool, condStr: string, msg = "") =
template checkJson(cond: untyped, msg = "") =
checkJsonImpl(cond, astToStr(cond), msg)

template fromJsonFields(a, b, T, keys) =
template fromJsonFields(a, b, T, keys, allowMissingFields) =
checkJson b.kind == JObject, $(b.kind) # we could customize whether to allow JNull
var num = 0
for key, val in fieldPairs(a):
num.inc
when key notin keys:
if b.hasKey key:
fromJson(val, b[key])
else:
# we could customize to allow this
elif not allowMissingFields:
checkJson false, $($T, key, b)
checkJson b.len == num, $(b.len, num, $T, b) # could customize
if not allowMissingFields:
checkJson b.len == num, $(b.len, num, $T, b)

proc fromJson*[T](a: var T, b: JsonNode) =
proc fromJson*[T](a: var T, b: JsonNode, allowMissingFields = false) =
## 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 @@ -152,10 +146,10 @@ proc fromJson*[T](a: var T, b: JsonNode) =
jsonTo(b[key], typ)
a = initCaseObject(T, fun)
const keys = getDiscriminants(T)
fromJsonFields(a, b, T, keys)
fromJsonFields(a, b, T, keys, allowMissingFields)
elif T is tuple:
when isNamedTuple(T):
fromJsonFields(a, b, T, seq[string].default)
fromJsonFields(a, b, T, seq[string].default, allowMissingFields)
else:
checkJson b.kind == JArray, $(b.kind) # we could customize whether to allow JNull
var i = 0
Expand All @@ -175,9 +169,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

0 comments on commit fe681f3

Please sign in to comment.