jsonutils.nim 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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 std/[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 std/macros
  30. from std/enumutils import symbolName
  31. from std/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. raiseAssert "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: raiseAssert $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: 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: raiseAssert "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. runnableExamples:
  344. import std/[tables, json, sugar]
  345. let foo = (
  346. t: [("two", 2)].toTable,
  347. ot: [("one", 1), ("three", 3)].toOrderedTable)
  348. assert $toJson(foo) == """{"t":{"two":2},"ot":{"one":1,"three":3}}"""
  349. # if keys are not string|cstring, you can use this:
  350. let a = {10: "foo", 11: "bar"}.newOrderedTable
  351. let a2 = collect: (for k,v in a: (k,v))
  352. assert $toJson(a2) == """[[10,"foo"],[11,"bar"]]"""
  353. result = newJObject()
  354. for k, v in pairs(t):
  355. # not sure if $k has overhead for string
  356. result[(when K is string: k else: $k)] = toJson(v, opt)
  357. proc fromJsonHook*[A](s: var SomeSet[A], jsonNode: JsonNode, opt = Joptions()) =
  358. ## Enables `fromJson` for `HashSet` and `OrderedSet` types.
  359. ##
  360. ## See also:
  361. ## * `toJsonHook proc<#toJsonHook,SomeSet[A]>`_
  362. runnableExamples:
  363. import std/[sets, json]
  364. var foo: tuple[hs: HashSet[string], os: OrderedSet[string]]
  365. fromJson(foo, parseJson("""
  366. {"hs": ["hash", "set"], "os": ["ordered", "set"]}"""))
  367. assert foo.hs == ["hash", "set"].toHashSet
  368. assert foo.os == ["ordered", "set"].toOrderedSet
  369. assert jsonNode.kind == JArray,
  370. "The kind of the `jsonNode` must be `JArray`, but its actual " &
  371. "type is `" & $jsonNode.kind & "`."
  372. clear(s)
  373. for v in jsonNode:
  374. incl(s, jsonTo(v, A, opt))
  375. proc toJsonHook*[A](s: SomeSet[A], opt = initToJsonOptions()): JsonNode =
  376. ## Enables `toJson` for `HashSet` and `OrderedSet` types.
  377. ##
  378. ## See also:
  379. ## * `fromJsonHook proc<#fromJsonHook,SomeSet[A],JsonNode>`_
  380. runnableExamples:
  381. import std/[sets, json]
  382. let foo = (hs: ["hash"].toHashSet, os: ["ordered", "set"].toOrderedSet)
  383. assert $toJson(foo) == """{"hs":["hash"],"os":["ordered","set"]}"""
  384. result = newJArray()
  385. for k in s:
  386. add(result, toJson(k, opt))
  387. proc fromJsonHook*[T](self: var Option[T], jsonNode: JsonNode, opt = Joptions()) =
  388. ## Enables `fromJson` for `Option` types.
  389. ##
  390. ## See also:
  391. ## * `toJsonHook proc<#toJsonHook,Option[T]>`_
  392. runnableExamples:
  393. import std/[options, json]
  394. var opt: Option[string]
  395. fromJsonHook(opt, parseJson("\"test\""))
  396. assert get(opt) == "test"
  397. fromJson(opt, parseJson("null"))
  398. assert isNone(opt)
  399. if jsonNode.kind != JNull:
  400. self = some(jsonTo(jsonNode, T, opt))
  401. else:
  402. self = none[T]()
  403. proc toJsonHook*[T](self: Option[T], opt = initToJsonOptions()): JsonNode =
  404. ## Enables `toJson` for `Option` types.
  405. ##
  406. ## See also:
  407. ## * `fromJsonHook proc<#fromJsonHook,Option[T],JsonNode>`_
  408. runnableExamples:
  409. import std/[options, json]
  410. let optSome = some("test")
  411. assert $toJson(optSome) == "\"test\""
  412. let optNone = none[string]()
  413. assert $toJson(optNone) == "null"
  414. if isSome(self):
  415. toJson(get(self), opt)
  416. else:
  417. newJNull()
  418. proc fromJsonHook*(a: var StringTableRef, b: JsonNode) =
  419. ## Enables `fromJson` for `StringTableRef` type.
  420. ##
  421. ## See also:
  422. ## * `toJsonHook proc<#toJsonHook,StringTableRef>`_
  423. runnableExamples:
  424. import std/[strtabs, json]
  425. var t = newStringTable(modeCaseSensitive)
  426. let jsonStr = """{"mode": 0, "table": {"name": "John", "surname": "Doe"}}"""
  427. fromJsonHook(t, parseJson(jsonStr))
  428. assert t[] == newStringTable("name", "John", "surname", "Doe",
  429. modeCaseSensitive)[]
  430. var mode = jsonTo(b["mode"], StringTableMode)
  431. a = newStringTable(mode)
  432. let b2 = b["table"]
  433. for k,v in b2: a[k] = jsonTo(v, string)
  434. proc toJsonHook*(a: StringTableRef): JsonNode =
  435. ## Enables `toJson` for `StringTableRef` type.
  436. ##
  437. ## See also:
  438. ## * `fromJsonHook proc<#fromJsonHook,StringTableRef,JsonNode>`_
  439. runnableExamples:
  440. import std/[strtabs, json]
  441. let t = newStringTable("name", "John", "surname", "Doe", modeCaseSensitive)
  442. let jsonStr = """{"mode": "modeCaseSensitive",
  443. "table": {"name": "John", "surname": "Doe"}}"""
  444. assert toJson(t) == parseJson(jsonStr)
  445. result = newJObject()
  446. result["mode"] = toJson($a.mode)
  447. let t = newJObject()
  448. for k,v in a: t[k] = toJson(v)
  449. result["table"] = t