jsonutils.nim 17 KB

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