jsonutils.nim 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. ##[
  2. This module implements a hookable (de)serialization for arbitrary types using JSON.
  3. Design goal: avoid importing modules where a custom serialization is needed;
  4. see strtabs.fromJsonHook,toJsonHook for an example.
  5. ]##
  6. runnableExamples:
  7. import std/[strtabs,json]
  8. type Foo = ref object
  9. t: bool
  10. z1: int8
  11. let a = (1.5'f32, (b: "b2", a: "a2"), 'x', @[Foo(t: true, z1: -3), nil], [{"name": "John"}.newStringTable])
  12. let j = a.toJson
  13. assert j.jsonTo(typeof(a)).toJson == j
  14. assert $[NaN, Inf, -Inf, 0.0, -0.0, 1.0, 1e-2].toJson == """["nan","inf","-inf",0.0,-0.0,1.0,0.01]"""
  15. assert 0.0.toJson.kind == JFloat
  16. assert Inf.toJson.kind == JString
  17. import json, strutils, tables, sets, strtabs, options, strformat
  18. #[
  19. Future directions:
  20. add a way to customize serialization, for e.g.:
  21. * field renaming
  22. * allow serializing `enum` and `char` as `string` instead of `int`
  23. (enum is more compact/efficient, and robust to enum renamings, but string
  24. is more human readable)
  25. * handle cyclic references, using a cache of already visited addresses
  26. * implement support for serialization and de-serialization of nested variant
  27. objects.
  28. ]#
  29. import macros
  30. from enumutils import symbolName
  31. from typetraits import OrdinalEnum, tupleLen
  32. when defined(nimPreviewSlimSystem):
  33. import std/assertions
  34. proc isNamedTuple(T: typedesc): bool {.magic: "TypeTrait".}
  35. type
  36. Joptions* = object # xxx rename FromJsonOptions
  37. ## Options controlling the behavior of `fromJson`.
  38. allowExtraKeys*: bool
  39. ## If `true` Nim's object to which the JSON is parsed is not required to
  40. ## have a field for every JSON key.
  41. allowMissingKeys*: bool
  42. ## If `true` Nim's object to which JSON is parsed is allowed to have
  43. ## fields without corresponding JSON keys.
  44. # in future work: a key rename could be added
  45. EnumMode* = enum
  46. joptEnumOrd
  47. joptEnumSymbol
  48. joptEnumString
  49. JsonNodeMode* = enum ## controls `toJson` for JsonNode types
  50. joptJsonNodeAsRef ## returns the ref as is
  51. joptJsonNodeAsCopy ## returns a deep copy of the JsonNode
  52. joptJsonNodeAsObject ## treats JsonNode as a regular ref object
  53. ToJsonOptions* = object
  54. enumMode*: EnumMode
  55. jsonNodeMode*: JsonNodeMode
  56. # xxx charMode, etc
  57. proc initToJsonOptions*(): ToJsonOptions =
  58. ## initializes `ToJsonOptions` with sane options.
  59. ToJsonOptions(enumMode: joptEnumOrd, jsonNodeMode: joptJsonNodeAsRef)
  60. proc distinctBase(T: typedesc, recursive: static bool = true): typedesc {.magic: "TypeTrait".}
  61. template distinctBase[T](a: T, recursive: static bool = true): untyped = distinctBase(typeof(a), recursive)(a)
  62. macro getDiscriminants(a: typedesc): seq[string] =
  63. ## return the discriminant keys
  64. # candidate for std/typetraits
  65. var a = a.getTypeImpl
  66. doAssert a.kind == nnkBracketExpr
  67. let sym = a[1]
  68. let t = sym.getTypeImpl
  69. let t2 = t[2]
  70. doAssert t2.kind == nnkRecList
  71. result = newTree(nnkBracket)
  72. for ti in t2:
  73. if ti.kind == nnkRecCase:
  74. let key = ti[0][0]
  75. let typ = ti[0][1]
  76. result.add newLit key.strVal
  77. if result.len > 0:
  78. result = quote do:
  79. @`result`
  80. else:
  81. result = quote do:
  82. seq[string].default
  83. macro initCaseObject(T: typedesc, fun: untyped): untyped =
  84. ## does the minimum to construct a valid case object, only initializing
  85. ## the discriminant fields; see also `getDiscriminants`
  86. # maybe candidate for std/typetraits
  87. var a = T.getTypeImpl
  88. doAssert a.kind == nnkBracketExpr
  89. let sym = a[1]
  90. let t = sym.getTypeImpl
  91. var t2: NimNode
  92. case t.kind
  93. of nnkObjectTy: t2 = t[2]
  94. of nnkRefTy: t2 = t[0].getTypeImpl[2]
  95. else: doAssert false, $t.kind # xxx `nnkPtrTy` could be handled too
  96. doAssert t2.kind == nnkRecList
  97. result = newTree(nnkObjConstr)
  98. result.add sym
  99. for ti in t2:
  100. if ti.kind == nnkRecCase:
  101. let key = ti[0][0]
  102. let typ = ti[0][1]
  103. let key2 = key.strVal
  104. let val = quote do:
  105. `fun`(`key2`, typedesc[`typ`])
  106. result.add newTree(nnkExprColonExpr, key, val)
  107. proc raiseJsonException(condStr: string, msg: string) {.noinline.} =
  108. # just pick 1 exception type for simplicity; other choices would be:
  109. # JsonError, JsonParser, JsonKindError
  110. raise newException(ValueError, condStr & " failed: " & msg)
  111. template checkJson(cond: untyped, msg = "") =
  112. if not cond:
  113. raiseJsonException(astToStr(cond), msg)
  114. proc hasField[T](obj: T, field: string): bool =
  115. for k, _ in fieldPairs(obj):
  116. if k == field:
  117. return true
  118. return false
  119. macro accessField(obj: typed, name: static string): untyped =
  120. newDotExpr(obj, ident(name))
  121. template fromJsonFields(newObj, oldObj, json, discKeys, opt) =
  122. type T = typeof(newObj)
  123. # we could customize whether to allow JNull
  124. checkJson json.kind == JObject, $json.kind
  125. var num, numMatched = 0
  126. for key, val in fieldPairs(newObj):
  127. num.inc
  128. when key notin discKeys:
  129. if json.hasKey key:
  130. numMatched.inc
  131. fromJson(val, json[key], opt)
  132. elif opt.allowMissingKeys:
  133. # if there are no discriminant keys the `oldObj` must always have the
  134. # same keys as the new one. Otherwise we must check, because they could
  135. # be set to different branches.
  136. when typeof(oldObj) isnot typeof(nil):
  137. if discKeys.len == 0 or hasField(oldObj, key):
  138. val = accessField(oldObj, key)
  139. else:
  140. checkJson false, "key '$1' for $2 not in $3" % [key, $T, json.pretty()]
  141. else:
  142. if json.hasKey key:
  143. numMatched.inc
  144. let ok =
  145. if opt.allowExtraKeys and opt.allowMissingKeys:
  146. true
  147. elif opt.allowExtraKeys:
  148. # This check is redundant because if here missing keys are not allowed,
  149. # and if `num != numMatched` it will fail in the loop above but it is left
  150. # for clarity.
  151. assert num == numMatched
  152. num == numMatched
  153. elif opt.allowMissingKeys:
  154. json.len == numMatched
  155. else:
  156. json.len == num and num == numMatched
  157. checkJson ok, "There were $1 keys (expecting $2) for $3 with $4" % [$json.len, $num, $T, json.pretty()]
  158. proc fromJson*[T](a: var T, b: JsonNode, opt = Joptions())
  159. proc discKeyMatch[T](obj: T, json: JsonNode, key: static string): bool =
  160. if not json.hasKey key:
  161. return true
  162. let field = accessField(obj, key)
  163. var jsonVal: typeof(field)
  164. fromJson(jsonVal, json[key])
  165. if jsonVal != field:
  166. return false
  167. return true
  168. macro discKeysMatchBodyGen(obj: typed, json: JsonNode,
  169. keys: static seq[string]): untyped =
  170. result = newStmtList()
  171. let r = ident("result")
  172. for key in keys:
  173. let keyLit = newLit key
  174. result.add quote do:
  175. `r` = `r` and discKeyMatch(`obj`, `json`, `keyLit`)
  176. proc discKeysMatch[T](obj: T, json: JsonNode, keys: static seq[string]): bool =
  177. result = true
  178. discKeysMatchBodyGen(obj, json, keys)
  179. proc fromJson*[T](a: var T, b: JsonNode, opt = Joptions()) =
  180. ## inplace version of `jsonTo`
  181. #[
  182. adding "json path" leading to `b` can be added in future work.
  183. ]#
  184. checkJson b != nil, $($T, b)
  185. when compiles(fromJsonHook(a, b, opt)): fromJsonHook(a, b, opt)
  186. elif compiles(fromJsonHook(a, b)): fromJsonHook(a, b)
  187. elif T is bool: a = to(b,T)
  188. elif T is enum:
  189. case b.kind
  190. of JInt: a = T(b.getBiggestInt())
  191. of JString: a = parseEnum[T](b.getStr())
  192. else: checkJson false, fmt"Expecting int/string for {$T} got {b.pretty()}"
  193. elif T is uint|uint64: a = T(to(b, uint64))
  194. elif T is Ordinal: a = cast[T](to(b, int))
  195. elif T is pointer: a = cast[pointer](to(b, int))
  196. elif T is distinct:
  197. when nimvm:
  198. # bug, potentially related to https://github.com/nim-lang/Nim/issues/12282
  199. a = T(jsonTo(b, distinctBase(T)))
  200. else:
  201. a.distinctBase.fromJson(b)
  202. elif T is string|SomeNumber: a = to(b,T)
  203. elif T is cstring:
  204. case b.kind
  205. of JNull: a = nil
  206. of JString: a = b.str
  207. else: checkJson false, fmt"Expecting null/string for {$T} got {b.pretty()}"
  208. elif T is JsonNode: a = b
  209. elif T is ref | ptr:
  210. if b.kind == JNull: a = nil
  211. else:
  212. a = T()
  213. fromJson(a[], b, opt)
  214. elif T is array:
  215. checkJson a.len == b.len, fmt"Json array size doesn't match for {$T}"
  216. var i = 0
  217. for ai in mitems(a):
  218. fromJson(ai, b[i], opt)
  219. i.inc
  220. elif T is set:
  221. type E = typeof(for ai in a: ai)
  222. for val in b.getElems:
  223. incl a, jsonTo(val, E)
  224. elif T is seq:
  225. a.setLen b.len
  226. for i, val in b.getElems:
  227. fromJson(a[i], val, opt)
  228. elif T is object:
  229. template fun(key, typ): untyped {.used.} =
  230. if b.hasKey key:
  231. jsonTo(b[key], typ)
  232. elif hasField(a, key):
  233. accessField(a, key)
  234. else:
  235. default(typ)
  236. const keys = getDiscriminants(T)
  237. when keys.len == 0:
  238. fromJsonFields(a, nil, b, keys, opt)
  239. else:
  240. if discKeysMatch(a, b, keys):
  241. fromJsonFields(a, nil, b, keys, opt)
  242. else:
  243. var newObj = initCaseObject(T, fun)
  244. fromJsonFields(newObj, a, b, keys, opt)
  245. a = newObj
  246. elif T is tuple:
  247. when isNamedTuple(T):
  248. fromJsonFields(a, nil, b, seq[string].default, opt)
  249. else:
  250. checkJson b.kind == JArray, $(b.kind) # we could customize whether to allow JNull
  251. when compiles(tupleLen(T)):
  252. let tupleSize = tupleLen(T)
  253. else:
  254. # Tuple len isn't in csources_v1 so using tupleLen would fail.
  255. # Else branch basically never runs (tupleLen added in 1.1 and jsonutils in 1.4), but here for consistency
  256. var tupleSize = 0
  257. for val in fields(a):
  258. tupleSize.inc
  259. checkJson b.len == tupleSize, fmt"Json doesn't match expected length of {tupleSize}, got {b.pretty()}"
  260. var i = 0
  261. for val in fields(a):
  262. fromJson(val, b[i], opt)
  263. i.inc
  264. else:
  265. # checkJson not appropriate here
  266. static: doAssert false, "not yet implemented: " & $T
  267. proc jsonTo*(b: JsonNode, T: typedesc, opt = Joptions()): T =
  268. ## reverse of `toJson`
  269. fromJson(result, b, opt)
  270. proc toJson*[T](a: T, opt = initToJsonOptions()): JsonNode =
  271. ## serializes `a` to json; uses `toJsonHook(a: T)` if it's in scope to
  272. ## customize serialization, see strtabs.toJsonHook for an example.
  273. ##
  274. ## .. note:: With `-d:nimPreviewJsonutilsHoleyEnum`, `toJson` now can
  275. ## serialize/deserialize holey enums as regular enums (via `ord`) instead of as strings.
  276. ## It is expected that this behavior becomes the new default in upcoming versions.
  277. when compiles(toJsonHook(a, opt)): result = toJsonHook(a, opt)
  278. elif compiles(toJsonHook(a)): result = toJsonHook(a)
  279. elif T is object | tuple:
  280. when T is object or isNamedTuple(T):
  281. result = newJObject()
  282. for k, v in a.fieldPairs: result[k] = toJson(v, opt)
  283. else:
  284. result = newJArray()
  285. for v in a.fields: result.add toJson(v, opt)
  286. elif T is ref | ptr:
  287. template impl =
  288. if system.`==`(a, nil): result = newJNull()
  289. else: result = toJson(a[], opt)
  290. when T is JsonNode:
  291. case opt.jsonNodeMode
  292. of joptJsonNodeAsRef: result = a
  293. of joptJsonNodeAsCopy: result = copy(a)
  294. of joptJsonNodeAsObject: impl()
  295. else: impl()
  296. elif T is array | seq | set:
  297. result = newJArray()
  298. for ai in a: result.add toJson(ai, opt)
  299. elif T is pointer: result = toJson(cast[int](a), opt)
  300. # edge case: `a == nil` could've also led to `newJNull()`, but this results
  301. # in simpler code for `toJson` and `fromJson`.
  302. elif T is distinct: result = toJson(a.distinctBase, opt)
  303. elif T is bool: result = %(a)
  304. elif T is SomeInteger: result = %a
  305. elif T is enum:
  306. case opt.enumMode
  307. of joptEnumOrd:
  308. when T is Ordinal or defined(nimPreviewJsonutilsHoleyEnum): %(a.ord)
  309. else: toJson($a, opt)
  310. of joptEnumSymbol:
  311. when T is OrdinalEnum:
  312. toJson(symbolName(a), opt)
  313. else:
  314. toJson($a, opt)
  315. of joptEnumString: toJson($a, opt)
  316. elif T is Ordinal: result = %(a.ord)
  317. elif T is cstring: (if a == nil: result = newJNull() else: result = % $a)
  318. else: result = %a
  319. proc fromJsonHook*[K: string|cstring, V](t: var (Table[K, V] | OrderedTable[K, V]),
  320. jsonNode: JsonNode, opt = Joptions()) =
  321. ## Enables `fromJson` for `Table` and `OrderedTable` types.
  322. ##
  323. ## See also:
  324. ## * `toJsonHook proc<#toJsonHook>`_
  325. runnableExamples:
  326. import std/[tables, json]
  327. var foo: tuple[t: Table[string, int], ot: OrderedTable[string, int]]
  328. fromJson(foo, parseJson("""
  329. {"t":{"two":2,"one":1},"ot":{"one":1,"three":3}}"""))
  330. assert foo.t == [("one", 1), ("two", 2)].toTable
  331. assert foo.ot == [("one", 1), ("three", 3)].toOrderedTable
  332. assert jsonNode.kind == JObject,
  333. "The kind of the `jsonNode` must be `JObject`, but its actual " &
  334. "type is `" & $jsonNode.kind & "`."
  335. clear(t)
  336. for k, v in jsonNode:
  337. t[k] = jsonTo(v, V, opt)
  338. proc toJsonHook*[K: string|cstring, V](t: (Table[K, V] | OrderedTable[K, V]), opt = initToJsonOptions()): JsonNode =
  339. ## Enables `toJson` for `Table` and `OrderedTable` types.
  340. ##
  341. ## See also:
  342. ## * `fromJsonHook proc<#fromJsonHook,,JsonNode>`_
  343. # pending PR #9217 use: toSeq(a) instead of `collect` in `runnableExamples`.
  344. runnableExamples:
  345. import std/[tables, json, sugar]
  346. let foo = (
  347. t: [("two", 2)].toTable,
  348. ot: [("one", 1), ("three", 3)].toOrderedTable)
  349. assert $toJson(foo) == """{"t":{"two":2},"ot":{"one":1,"three":3}}"""
  350. # if keys are not string|cstring, you can use this:
  351. let a = {10: "foo", 11: "bar"}.newOrderedTable
  352. let a2 = collect: (for k,v in a: (k,v))
  353. assert $toJson(a2) == """[[10,"foo"],[11,"bar"]]"""
  354. result = newJObject()
  355. for k, v in pairs(t):
  356. # not sure if $k has overhead for string
  357. result[(when K is string: k else: $k)] = toJson(v, opt)
  358. proc fromJsonHook*[A](s: var SomeSet[A], jsonNode: JsonNode, opt = Joptions()) =
  359. ## Enables `fromJson` for `HashSet` and `OrderedSet` types.
  360. ##
  361. ## See also:
  362. ## * `toJsonHook proc<#toJsonHook,SomeSet[A]>`_
  363. runnableExamples:
  364. import std/[sets, json]
  365. var foo: tuple[hs: HashSet[string], os: OrderedSet[string]]
  366. fromJson(foo, parseJson("""
  367. {"hs": ["hash", "set"], "os": ["ordered", "set"]}"""))
  368. assert foo.hs == ["hash", "set"].toHashSet
  369. assert foo.os == ["ordered", "set"].toOrderedSet
  370. assert jsonNode.kind == JArray,
  371. "The kind of the `jsonNode` must be `JArray`, but its actual " &
  372. "type is `" & $jsonNode.kind & "`."
  373. clear(s)
  374. for v in jsonNode:
  375. incl(s, jsonTo(v, A, opt))
  376. proc toJsonHook*[A](s: SomeSet[A], opt = initToJsonOptions()): JsonNode =
  377. ## Enables `toJson` for `HashSet` and `OrderedSet` types.
  378. ##
  379. ## See also:
  380. ## * `fromJsonHook proc<#fromJsonHook,SomeSet[A],JsonNode>`_
  381. runnableExamples:
  382. import std/[sets, json]
  383. let foo = (hs: ["hash"].toHashSet, os: ["ordered", "set"].toOrderedSet)
  384. assert $toJson(foo) == """{"hs":["hash"],"os":["ordered","set"]}"""
  385. result = newJArray()
  386. for k in s:
  387. add(result, toJson(k, opt))
  388. proc fromJsonHook*[T](self: var Option[T], jsonNode: JsonNode, opt = Joptions()) =
  389. ## Enables `fromJson` for `Option` types.
  390. ##
  391. ## See also:
  392. ## * `toJsonHook proc<#toJsonHook,Option[T]>`_
  393. runnableExamples:
  394. import std/[options, json]
  395. var opt: Option[string]
  396. fromJsonHook(opt, parseJson("\"test\""))
  397. assert get(opt) == "test"
  398. fromJson(opt, parseJson("null"))
  399. assert isNone(opt)
  400. if jsonNode.kind != JNull:
  401. self = some(jsonTo(jsonNode, T, opt))
  402. else:
  403. self = none[T]()
  404. proc toJsonHook*[T](self: Option[T], opt = initToJsonOptions()): JsonNode =
  405. ## Enables `toJson` for `Option` types.
  406. ##
  407. ## See also:
  408. ## * `fromJsonHook proc<#fromJsonHook,Option[T],JsonNode>`_
  409. runnableExamples:
  410. import std/[options, json]
  411. let optSome = some("test")
  412. assert $toJson(optSome) == "\"test\""
  413. let optNone = none[string]()
  414. assert $toJson(optNone) == "null"
  415. if isSome(self):
  416. toJson(get(self), opt)
  417. else:
  418. newJNull()
  419. proc fromJsonHook*(a: var StringTableRef, b: JsonNode) =
  420. ## Enables `fromJson` for `StringTableRef` type.
  421. ##
  422. ## See also:
  423. ## * `toJsonHook proc<#toJsonHook,StringTableRef>`_
  424. runnableExamples:
  425. import std/[strtabs, json]
  426. var t = newStringTable(modeCaseSensitive)
  427. let jsonStr = """{"mode": 0, "table": {"name": "John", "surname": "Doe"}}"""
  428. fromJsonHook(t, parseJson(jsonStr))
  429. assert t[] == newStringTable("name", "John", "surname", "Doe",
  430. modeCaseSensitive)[]
  431. var mode = jsonTo(b["mode"], StringTableMode)
  432. a = newStringTable(mode)
  433. let b2 = b["table"]
  434. for k,v in b2: a[k] = jsonTo(v, string)
  435. proc toJsonHook*(a: StringTableRef): JsonNode =
  436. ## Enables `toJson` for `StringTableRef` type.
  437. ##
  438. ## See also:
  439. ## * `fromJsonHook proc<#fromJsonHook,StringTableRef,JsonNode>`_
  440. runnableExamples:
  441. import std/[strtabs, json]
  442. let t = newStringTable("name", "John", "surname", "Doe", modeCaseSensitive)
  443. let jsonStr = """{"mode": "modeCaseSensitive",
  444. "table": {"name": "John", "surname": "Doe"}}"""
  445. assert toJson(t) == parseJson(jsonStr)
  446. result = newJObject()
  447. result["mode"] = toJson($a.mode)
  448. let t = newJObject()
  449. for k,v in a: t[k] = toJson(v)
  450. result["table"] = t