json.nim 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf, Dominik Picheta
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements a simple high performance `JSON`:idx:
  10. ## parser. JSON (JavaScript Object Notation) is a lightweight
  11. ## data-interchange format that is easy for humans to read and write
  12. ## (unlike XML). It is easy for machines to parse and generate.
  13. ## JSON is based on a subset of the JavaScript Programming Language,
  14. ## Standard ECMA-262 3rd Edition - December 1999.
  15. ##
  16. ## See also
  17. ## ========
  18. ## * `std/parsejson <parsejson.html>`_
  19. ## * `std/jsonutils <jsonutils.html>`_
  20. ## * `std/marshal <marshal.html>`_
  21. ## * `std/jscore <jscore.html>`_
  22. ##
  23. ##
  24. ## Overview
  25. ## ========
  26. ##
  27. ## Parsing JSON
  28. ## ------------
  29. ##
  30. ## JSON often arrives into your program (via an API or a file) as a `string`.
  31. ## The first step is to change it from its serialized form into a nested object
  32. ## structure called a `JsonNode`.
  33. ##
  34. ## The `parseJson` procedure takes a string containing JSON and returns a
  35. ## `JsonNode` object. This is an object variant and it is either a
  36. ## `JObject`, `JArray`, `JString`, `JInt`, `JFloat`, `JBool` or
  37. ## `JNull`. You check the kind of this object variant by using the `kind`
  38. ## accessor.
  39. ##
  40. ## For a `JsonNode` who's kind is `JObject`, you can access its fields using
  41. ## the `[]` operator. The following example shows how to do this:
  42. ##
  43. ## .. code-block:: Nim
  44. ## import std/json
  45. ##
  46. ## let jsonNode = parseJson("""{"key": 3.14}""")
  47. ##
  48. ## doAssert jsonNode.kind == JObject
  49. ## doAssert jsonNode["key"].kind == JFloat
  50. ##
  51. ## Reading values
  52. ## --------------
  53. ##
  54. ## Once you have a `JsonNode`, retrieving the values can then be achieved
  55. ## by using one of the helper procedures, which include:
  56. ##
  57. ## * `getInt`
  58. ## * `getFloat`
  59. ## * `getStr`
  60. ## * `getBool`
  61. ##
  62. ## To retrieve the value of `"key"` you can do the following:
  63. ##
  64. ## .. code-block:: Nim
  65. ## import std/json
  66. ##
  67. ## let jsonNode = parseJson("""{"key": 3.14}""")
  68. ##
  69. ## doAssert jsonNode["key"].getFloat() == 3.14
  70. ##
  71. ## **Important:** The `[]` operator will raise an exception when the
  72. ## specified field does not exist.
  73. ##
  74. ## Handling optional keys
  75. ## ----------------------
  76. ##
  77. ## By using the `{}` operator instead of `[]`, it will return `nil`
  78. ## when the field is not found. The `get`-family of procedures will return a
  79. ## type's default value when called on `nil`.
  80. ##
  81. ## .. code-block:: Nim
  82. ## import std/json
  83. ##
  84. ## let jsonNode = parseJson("{}")
  85. ##
  86. ## doAssert jsonNode{"nope"}.getInt() == 0
  87. ## doAssert jsonNode{"nope"}.getFloat() == 0
  88. ## doAssert jsonNode{"nope"}.getStr() == ""
  89. ## doAssert jsonNode{"nope"}.getBool() == false
  90. ##
  91. ## Using default values
  92. ## --------------------
  93. ##
  94. ## The `get`-family helpers also accept an additional parameter which allow
  95. ## you to fallback to a default value should the key's values be `null`:
  96. ##
  97. ## .. code-block:: Nim
  98. ## import std/json
  99. ##
  100. ## let jsonNode = parseJson("""{"key": 3.14, "key2": null}""")
  101. ##
  102. ## doAssert jsonNode["key"].getFloat(6.28) == 3.14
  103. ## doAssert jsonNode["key2"].getFloat(3.14) == 3.14
  104. ## doAssert jsonNode{"nope"}.getFloat(3.14) == 3.14 # note the {}
  105. ##
  106. ## Unmarshalling
  107. ## -------------
  108. ##
  109. ## In addition to reading dynamic data, Nim can also unmarshal JSON directly
  110. ## into a type with the `to` macro.
  111. ##
  112. ## Note: Use `Option <options.html#Option>`_ for keys sometimes missing in json
  113. ## responses, and backticks around keys with a reserved keyword as name.
  114. ##
  115. ## .. code-block:: Nim
  116. ## import std/json
  117. ## import std/options
  118. ##
  119. ## type
  120. ## User = object
  121. ## name: string
  122. ## age: int
  123. ## `type`: Option[string]
  124. ##
  125. ## let userJson = parseJson("""{ "name": "Nim", "age": 12 }""")
  126. ## let user = to(userJson, User)
  127. ## if user.`type`.isSome():
  128. ## assert user.`type`.get() != "robot"
  129. ##
  130. ## Creating JSON
  131. ## =============
  132. ##
  133. ## This module can also be used to comfortably create JSON using the `%*`
  134. ## operator:
  135. ##
  136. ## .. code-block:: nim
  137. ## import std/json
  138. ##
  139. ## var hisName = "John"
  140. ## let herAge = 31
  141. ## var j = %*
  142. ## [
  143. ## { "name": hisName, "age": 30 },
  144. ## { "name": "Susan", "age": herAge }
  145. ## ]
  146. ##
  147. ## var j2 = %* {"name": "Isaac", "books": ["Robot Dreams"]}
  148. ## j2["details"] = %* {"age":35, "pi":3.1415}
  149. ## echo j2
  150. ##
  151. ## See also: std/jsonutils for hookable json serialization/deserialization
  152. ## of arbitrary types.
  153. runnableExamples:
  154. ## Note: for JObject, key ordering is preserved, unlike in some languages,
  155. ## this is convenient for some use cases. Example:
  156. type Foo = object
  157. a1, a2, a0, a3, a4: int
  158. doAssert $(%* Foo()) == """{"a1":0,"a2":0,"a0":0,"a3":0,"a4":0}"""
  159. import hashes, tables, strutils, lexbase, streams, macros, parsejson
  160. import options # xxx remove this dependency using same approach as https://github.com/nim-lang/Nim/pull/14563
  161. import std/private/since
  162. when defined(nimPreviewSlimSystem):
  163. import std/[syncio, assertions, formatfloat]
  164. export
  165. tables.`$`
  166. export
  167. parsejson.JsonEventKind, parsejson.JsonError, JsonParser, JsonKindError,
  168. open, close, str, getInt, getFloat, kind, getColumn, getLine, getFilename,
  169. errorMsg, errorMsgExpected, next, JsonParsingError, raiseParseErr, nimIdentNormalize
  170. type
  171. JsonNodeKind* = enum ## possible JSON node types
  172. JNull,
  173. JBool,
  174. JInt,
  175. JFloat,
  176. JString,
  177. JObject,
  178. JArray
  179. JsonNode* = ref JsonNodeObj ## JSON node
  180. JsonNodeObj* {.acyclic.} = object
  181. isUnquoted: bool # the JString was a number-like token and
  182. # so shouldn't be quoted
  183. case kind*: JsonNodeKind
  184. of JString:
  185. str*: string
  186. of JInt:
  187. num*: BiggestInt
  188. of JFloat:
  189. fnum*: float
  190. of JBool:
  191. bval*: bool
  192. of JNull:
  193. nil
  194. of JObject:
  195. fields*: OrderedTable[string, JsonNode]
  196. of JArray:
  197. elems*: seq[JsonNode]
  198. const DepthLimit = 1000
  199. proc newJString*(s: string): JsonNode =
  200. ## Creates a new `JString JsonNode`.
  201. result = JsonNode(kind: JString, str: s)
  202. proc newJRawNumber(s: string): JsonNode =
  203. ## Creates a "raw JS number", that is a number that does not
  204. ## fit into Nim's `BiggestInt` field. This is really a `JString`
  205. ## with the additional information that it should be converted back
  206. ## to the string representation without the quotes.
  207. result = JsonNode(kind: JString, str: s, isUnquoted: true)
  208. proc newJInt*(n: BiggestInt): JsonNode =
  209. ## Creates a new `JInt JsonNode`.
  210. result = JsonNode(kind: JInt, num: n)
  211. proc newJFloat*(n: float): JsonNode =
  212. ## Creates a new `JFloat JsonNode`.
  213. result = JsonNode(kind: JFloat, fnum: n)
  214. proc newJBool*(b: bool): JsonNode =
  215. ## Creates a new `JBool JsonNode`.
  216. result = JsonNode(kind: JBool, bval: b)
  217. proc newJNull*(): JsonNode =
  218. ## Creates a new `JNull JsonNode`.
  219. result = JsonNode(kind: JNull)
  220. proc newJObject*(): JsonNode =
  221. ## Creates a new `JObject JsonNode`
  222. result = JsonNode(kind: JObject, fields: initOrderedTable[string, JsonNode](2))
  223. proc newJArray*(): JsonNode =
  224. ## Creates a new `JArray JsonNode`
  225. result = JsonNode(kind: JArray, elems: @[])
  226. proc getStr*(n: JsonNode, default: string = ""): string =
  227. ## Retrieves the string value of a `JString JsonNode`.
  228. ##
  229. ## Returns `default` if `n` is not a `JString`, or if `n` is nil.
  230. if n.isNil or n.kind != JString: return default
  231. else: return n.str
  232. proc getInt*(n: JsonNode, default: int = 0): int =
  233. ## Retrieves the int value of a `JInt JsonNode`.
  234. ##
  235. ## Returns `default` if `n` is not a `JInt`, or if `n` is nil.
  236. if n.isNil or n.kind != JInt: return default
  237. else: return int(n.num)
  238. proc getBiggestInt*(n: JsonNode, default: BiggestInt = 0): BiggestInt =
  239. ## Retrieves the BiggestInt value of a `JInt JsonNode`.
  240. ##
  241. ## Returns `default` if `n` is not a `JInt`, or if `n` is nil.
  242. if n.isNil or n.kind != JInt: return default
  243. else: return n.num
  244. proc getFloat*(n: JsonNode, default: float = 0.0): float =
  245. ## Retrieves the float value of a `JFloat JsonNode`.
  246. ##
  247. ## Returns `default` if `n` is not a `JFloat` or `JInt`, or if `n` is nil.
  248. if n.isNil: return default
  249. case n.kind
  250. of JFloat: return n.fnum
  251. of JInt: return float(n.num)
  252. else: return default
  253. proc getBool*(n: JsonNode, default: bool = false): bool =
  254. ## Retrieves the bool value of a `JBool JsonNode`.
  255. ##
  256. ## Returns `default` if `n` is not a `JBool`, or if `n` is nil.
  257. if n.isNil or n.kind != JBool: return default
  258. else: return n.bval
  259. proc getFields*(n: JsonNode,
  260. default = initOrderedTable[string, JsonNode](2)):
  261. OrderedTable[string, JsonNode] =
  262. ## Retrieves the key, value pairs of a `JObject JsonNode`.
  263. ##
  264. ## Returns `default` if `n` is not a `JObject`, or if `n` is nil.
  265. if n.isNil or n.kind != JObject: return default
  266. else: return n.fields
  267. proc getElems*(n: JsonNode, default: seq[JsonNode] = @[]): seq[JsonNode] =
  268. ## Retrieves the array of a `JArray JsonNode`.
  269. ##
  270. ## Returns `default` if `n` is not a `JArray`, or if `n` is nil.
  271. if n.isNil or n.kind != JArray: return default
  272. else: return n.elems
  273. proc add*(father, child: JsonNode) =
  274. ## Adds `child` to a JArray node `father`.
  275. assert father.kind == JArray
  276. father.elems.add(child)
  277. proc add*(obj: JsonNode, key: string, val: JsonNode) =
  278. ## Sets a field from a `JObject`.
  279. assert obj.kind == JObject
  280. obj.fields[key] = val
  281. proc `%`*(s: string): JsonNode =
  282. ## Generic constructor for JSON data. Creates a new `JString JsonNode`.
  283. result = JsonNode(kind: JString, str: s)
  284. proc `%`*(n: uint): JsonNode =
  285. ## Generic constructor for JSON data. Creates a new `JInt JsonNode`.
  286. if n > cast[uint](int.high):
  287. result = newJRawNumber($n)
  288. else:
  289. result = JsonNode(kind: JInt, num: BiggestInt(n))
  290. proc `%`*(n: int): JsonNode =
  291. ## Generic constructor for JSON data. Creates a new `JInt JsonNode`.
  292. result = JsonNode(kind: JInt, num: n)
  293. proc `%`*(n: BiggestUInt): JsonNode =
  294. ## Generic constructor for JSON data. Creates a new `JInt JsonNode`.
  295. if n > cast[BiggestUInt](BiggestInt.high):
  296. result = newJRawNumber($n)
  297. else:
  298. result = JsonNode(kind: JInt, num: BiggestInt(n))
  299. proc `%`*(n: BiggestInt): JsonNode =
  300. ## Generic constructor for JSON data. Creates a new `JInt JsonNode`.
  301. result = JsonNode(kind: JInt, num: n)
  302. proc `%`*(n: float): JsonNode =
  303. ## Generic constructor for JSON data. Creates a new `JFloat JsonNode`.
  304. runnableExamples:
  305. assert $(%[NaN, Inf, -Inf, 0.0, -0.0, 1.0, 1e-2]) == """["nan","inf","-inf",0.0,-0.0,1.0,0.01]"""
  306. assert (%NaN).kind == JString
  307. assert (%0.0).kind == JFloat
  308. # for those special cases, we could also have used `newJRawNumber` but then
  309. # it would've been inconsisten with the case of `parseJson` vs `%` for representing them.
  310. if n != n: newJString("nan")
  311. elif n == Inf: newJString("inf")
  312. elif n == -Inf: newJString("-inf")
  313. else: JsonNode(kind: JFloat, fnum: n)
  314. proc `%`*(b: bool): JsonNode =
  315. ## Generic constructor for JSON data. Creates a new `JBool JsonNode`.
  316. result = JsonNode(kind: JBool, bval: b)
  317. proc `%`*(keyVals: openArray[tuple[key: string, val: JsonNode]]): JsonNode =
  318. ## Generic constructor for JSON data. Creates a new `JObject JsonNode`
  319. if keyVals.len == 0: return newJArray()
  320. result = newJObject()
  321. for key, val in items(keyVals): result.fields[key] = val
  322. template `%`*(j: JsonNode): JsonNode = j
  323. proc `%`*[T](elements: openArray[T]): JsonNode =
  324. ## Generic constructor for JSON data. Creates a new `JArray JsonNode`
  325. result = newJArray()
  326. for elem in elements: result.add(%elem)
  327. proc `%`*[T](table: Table[string, T]|OrderedTable[string, T]): JsonNode =
  328. ## Generic constructor for JSON data. Creates a new `JObject JsonNode`.
  329. result = newJObject()
  330. for k, v in table: result[k] = %v
  331. proc `%`*[T](opt: Option[T]): JsonNode =
  332. ## Generic constructor for JSON data. Creates a new `JNull JsonNode`
  333. ## if `opt` is empty, otherwise it delegates to the underlying value.
  334. if opt.isSome: %opt.get else: newJNull()
  335. when false:
  336. # For 'consistency' we could do this, but that only pushes people further
  337. # into that evil comfort zone where they can use Nim without understanding it
  338. # causing problems later on.
  339. proc `%`*(elements: set[bool]): JsonNode =
  340. ## Generic constructor for JSON data. Creates a new `JObject JsonNode`.
  341. ## This can only be used with the empty set `{}` and is supported
  342. ## to prevent the gotcha `%*{}` which used to produce an empty
  343. ## JSON array.
  344. result = newJObject()
  345. assert false notin elements, "usage error: only empty sets allowed"
  346. assert true notin elements, "usage error: only empty sets allowed"
  347. proc `[]=`*(obj: JsonNode, key: string, val: JsonNode) {.inline.} =
  348. ## Sets a field from a `JObject`.
  349. assert(obj.kind == JObject)
  350. obj.fields[key] = val
  351. proc `%`*[T: object](o: T): JsonNode =
  352. ## Construct JsonNode from tuples and objects.
  353. result = newJObject()
  354. for k, v in o.fieldPairs: result[k] = %v
  355. proc `%`*(o: ref object): JsonNode =
  356. ## Generic constructor for JSON data. Creates a new `JObject JsonNode`
  357. if o.isNil:
  358. result = newJNull()
  359. else:
  360. result = %(o[])
  361. proc `%`*(o: enum): JsonNode =
  362. ## Construct a JsonNode that represents the specified enum value as a
  363. ## string. Creates a new `JString JsonNode`.
  364. result = %($o)
  365. proc toJsonImpl(x: NimNode): NimNode =
  366. case x.kind
  367. of nnkBracket: # array
  368. if x.len == 0: return newCall(bindSym"newJArray")
  369. result = newNimNode(nnkBracket)
  370. for i in 0 ..< x.len:
  371. result.add(toJsonImpl(x[i]))
  372. result = newCall(bindSym("%", brOpen), result)
  373. of nnkTableConstr: # object
  374. if x.len == 0: return newCall(bindSym"newJObject")
  375. result = newNimNode(nnkTableConstr)
  376. for i in 0 ..< x.len:
  377. x[i].expectKind nnkExprColonExpr
  378. result.add newTree(nnkExprColonExpr, x[i][0], toJsonImpl(x[i][1]))
  379. result = newCall(bindSym("%", brOpen), result)
  380. of nnkCurly: # empty object
  381. x.expectLen(0)
  382. result = newCall(bindSym"newJObject")
  383. of nnkNilLit:
  384. result = newCall(bindSym"newJNull")
  385. of nnkPar:
  386. if x.len == 1: result = toJsonImpl(x[0])
  387. else: result = newCall(bindSym("%", brOpen), x)
  388. else:
  389. result = newCall(bindSym("%", brOpen), x)
  390. macro `%*`*(x: untyped): untyped =
  391. ## Convert an expression to a JsonNode directly, without having to specify
  392. ## `%` for every element.
  393. result = toJsonImpl(x)
  394. proc `==`*(a, b: JsonNode): bool {.noSideEffect.} =
  395. ## Check two nodes for equality
  396. if a.isNil:
  397. if b.isNil: return true
  398. return false
  399. elif b.isNil or a.kind != b.kind:
  400. return false
  401. else:
  402. case a.kind
  403. of JString:
  404. result = a.str == b.str
  405. of JInt:
  406. result = a.num == b.num
  407. of JFloat:
  408. result = a.fnum == b.fnum
  409. of JBool:
  410. result = a.bval == b.bval
  411. of JNull:
  412. result = true
  413. of JArray:
  414. result = a.elems == b.elems
  415. of JObject:
  416. # we cannot use OrderedTable's equality here as
  417. # the order does not matter for equality here.
  418. if a.fields.len != b.fields.len: return false
  419. for key, val in a.fields:
  420. if not b.fields.hasKey(key): return false
  421. {.cast(raises: []).}:
  422. when defined(nimHasEffectsOf):
  423. {.noSideEffect.}:
  424. if b.fields[key] != val: return false
  425. else:
  426. if b.fields[key] != val: return false
  427. result = true
  428. proc hash*(n: OrderedTable[string, JsonNode]): Hash {.noSideEffect.}
  429. proc hash*(n: JsonNode): Hash {.noSideEffect.} =
  430. ## Compute the hash for a JSON node
  431. case n.kind
  432. of JArray:
  433. result = hash(n.elems)
  434. of JObject:
  435. result = hash(n.fields)
  436. of JInt:
  437. result = hash(n.num)
  438. of JFloat:
  439. result = hash(n.fnum)
  440. of JBool:
  441. result = hash(n.bval.int)
  442. of JString:
  443. result = hash(n.str)
  444. of JNull:
  445. result = Hash(0)
  446. proc hash*(n: OrderedTable[string, JsonNode]): Hash =
  447. for key, val in n:
  448. result = result xor (hash(key) !& hash(val))
  449. result = !$result
  450. proc len*(n: JsonNode): int =
  451. ## If `n` is a `JArray`, it returns the number of elements.
  452. ## If `n` is a `JObject`, it returns the number of pairs.
  453. ## Else it returns 0.
  454. case n.kind
  455. of JArray: result = n.elems.len
  456. of JObject: result = n.fields.len
  457. else: discard
  458. proc `[]`*(node: JsonNode, name: string): JsonNode {.inline.} =
  459. ## Gets a field from a `JObject`, which must not be nil.
  460. ## If the value at `name` does not exist, raises KeyError.
  461. assert(not isNil(node))
  462. assert(node.kind == JObject)
  463. when defined(nimJsonGet):
  464. if not node.fields.hasKey(name): return nil
  465. result = node.fields[name]
  466. proc `[]`*(node: JsonNode, index: int): JsonNode {.inline.} =
  467. ## Gets the node at `index` in an Array. Result is undefined if `index`
  468. ## is out of bounds, but as long as array bound checks are enabled it will
  469. ## result in an exception.
  470. assert(not isNil(node))
  471. assert(node.kind == JArray)
  472. return node.elems[index]
  473. proc `[]`*(node: JsonNode, index: BackwardsIndex): JsonNode {.inline, since: (1, 5, 1).} =
  474. ## Gets the node at `array.len-i` in an array through the `^` operator.
  475. ##
  476. ## i.e. `j[^i]` is a shortcut for `j[j.len-i]`.
  477. runnableExamples:
  478. let
  479. j = parseJson("[1,2,3,4,5]")
  480. doAssert j[^1].getInt == 5
  481. doAssert j[^2].getInt == 4
  482. `[]`(node, node.len - int(index))
  483. proc `[]`*[U, V](a: JsonNode, x: HSlice[U, V]): JsonNode =
  484. ## Slice operation for JArray.
  485. ##
  486. ## Returns the inclusive range `[a[x.a], a[x.b]]`:
  487. runnableExamples:
  488. import json
  489. let arr = %[0,1,2,3,4,5]
  490. doAssert arr[2..4] == %[2,3,4]
  491. doAssert arr[2..^2] == %[2,3,4]
  492. doAssert arr[^4..^2] == %[2,3,4]
  493. assert(a.kind == JArray)
  494. result = newJArray()
  495. let xa = (when x.a is BackwardsIndex: a.len - int(x.a) else: int(x.a))
  496. let L = (when x.b is BackwardsIndex: a.len - int(x.b) else: int(x.b)) - xa + 1
  497. for i in 0..<L:
  498. result.add(a[i + xa])
  499. proc hasKey*(node: JsonNode, key: string): bool =
  500. ## Checks if `key` exists in `node`.
  501. assert(node.kind == JObject)
  502. result = node.fields.hasKey(key)
  503. proc contains*(node: JsonNode, key: string): bool =
  504. ## Checks if `key` exists in `node`.
  505. assert(node.kind == JObject)
  506. node.fields.hasKey(key)
  507. proc contains*(node: JsonNode, val: JsonNode): bool =
  508. ## Checks if `val` exists in array `node`.
  509. assert(node.kind == JArray)
  510. find(node.elems, val) >= 0
  511. proc `{}`*(node: JsonNode, keys: varargs[string]): JsonNode =
  512. ## Traverses the node and gets the given value. If any of the
  513. ## keys do not exist, returns `nil`. Also returns `nil` if one of the
  514. ## intermediate data structures is not an object.
  515. ##
  516. ## This proc can be used to create tree structures on the
  517. ## fly (sometimes called `autovivification`:idx:):
  518. ##
  519. runnableExamples:
  520. var myjson = %* {"parent": {"child": {"grandchild": 1}}}
  521. doAssert myjson{"parent", "child", "grandchild"} == newJInt(1)
  522. result = node
  523. for key in keys:
  524. if isNil(result) or result.kind != JObject:
  525. return nil
  526. result = result.fields.getOrDefault(key)
  527. proc `{}`*(node: JsonNode, index: varargs[int]): JsonNode =
  528. ## Traverses the node and gets the given value. If any of the
  529. ## indexes do not exist, returns `nil`. Also returns `nil` if one of the
  530. ## intermediate data structures is not an array.
  531. result = node
  532. for i in index:
  533. if isNil(result) or result.kind != JArray or i >= node.len:
  534. return nil
  535. result = result.elems[i]
  536. proc getOrDefault*(node: JsonNode, key: string): JsonNode =
  537. ## Gets a field from a `node`. If `node` is nil or not an object or
  538. ## value at `key` does not exist, returns nil
  539. if not isNil(node) and node.kind == JObject:
  540. result = node.fields.getOrDefault(key)
  541. proc `{}`*(node: JsonNode, key: string): JsonNode =
  542. ## Gets a field from a `node`. If `node` is nil or not an object or
  543. ## value at `key` does not exist, returns nil
  544. node.getOrDefault(key)
  545. proc `{}=`*(node: JsonNode, keys: varargs[string], value: JsonNode) =
  546. ## Traverses the node and tries to set the value at the given location
  547. ## to `value`. If any of the keys are missing, they are added.
  548. var node = node
  549. for i in 0..(keys.len-2):
  550. if not node.hasKey(keys[i]):
  551. node[keys[i]] = newJObject()
  552. node = node[keys[i]]
  553. node[keys[keys.len-1]] = value
  554. proc delete*(obj: JsonNode, key: string) =
  555. ## Deletes `obj[key]`.
  556. assert(obj.kind == JObject)
  557. if not obj.fields.hasKey(key):
  558. raise newException(KeyError, "key not in object")
  559. obj.fields.del(key)
  560. proc copy*(p: JsonNode): JsonNode =
  561. ## Performs a deep copy of `a`.
  562. case p.kind
  563. of JString:
  564. result = newJString(p.str)
  565. result.isUnquoted = p.isUnquoted
  566. of JInt:
  567. result = newJInt(p.num)
  568. of JFloat:
  569. result = newJFloat(p.fnum)
  570. of JBool:
  571. result = newJBool(p.bval)
  572. of JNull:
  573. result = newJNull()
  574. of JObject:
  575. result = newJObject()
  576. for key, val in pairs(p.fields):
  577. result.fields[key] = copy(val)
  578. of JArray:
  579. result = newJArray()
  580. for i in items(p.elems):
  581. result.elems.add(copy(i))
  582. # ------------- pretty printing ----------------------------------------------
  583. proc indent(s: var string, i: int) =
  584. s.add(spaces(i))
  585. proc newIndent(curr, indent: int, ml: bool): int =
  586. if ml: return curr + indent
  587. else: return indent
  588. proc nl(s: var string, ml: bool) =
  589. s.add(if ml: "\n" else: " ")
  590. proc escapeJsonUnquoted*(s: string; result: var string) =
  591. ## Converts a string `s` to its JSON representation without quotes.
  592. ## Appends to `result`.
  593. for c in s:
  594. case c
  595. of '\L': result.add("\\n")
  596. of '\b': result.add("\\b")
  597. of '\f': result.add("\\f")
  598. of '\t': result.add("\\t")
  599. of '\v': result.add("\\u000b")
  600. of '\r': result.add("\\r")
  601. of '"': result.add("\\\"")
  602. of '\0'..'\7': result.add("\\u000" & $ord(c))
  603. of '\14'..'\31': result.add("\\u00" & toHex(ord(c), 2))
  604. of '\\': result.add("\\\\")
  605. else: result.add(c)
  606. proc escapeJsonUnquoted*(s: string): string =
  607. ## Converts a string `s` to its JSON representation without quotes.
  608. result = newStringOfCap(s.len + s.len shr 3)
  609. escapeJsonUnquoted(s, result)
  610. proc escapeJson*(s: string; result: var string) =
  611. ## Converts a string `s` to its JSON representation with quotes.
  612. ## Appends to `result`.
  613. result.add("\"")
  614. escapeJsonUnquoted(s, result)
  615. result.add("\"")
  616. proc escapeJson*(s: string): string =
  617. ## Converts a string `s` to its JSON representation with quotes.
  618. result = newStringOfCap(s.len + s.len shr 3)
  619. escapeJson(s, result)
  620. proc toUgly*(result: var string, node: JsonNode) =
  621. ## Converts `node` to its JSON Representation, without
  622. ## regard for human readability. Meant to improve `$` string
  623. ## conversion performance.
  624. ##
  625. ## JSON representation is stored in the passed `result`
  626. ##
  627. ## This provides higher efficiency than the `pretty` procedure as it
  628. ## does **not** attempt to format the resulting JSON to make it human readable.
  629. var comma = false
  630. case node.kind:
  631. of JArray:
  632. result.add "["
  633. for child in node.elems:
  634. if comma: result.add ","
  635. else: comma = true
  636. result.toUgly child
  637. result.add "]"
  638. of JObject:
  639. result.add "{"
  640. for key, value in pairs(node.fields):
  641. if comma: result.add ","
  642. else: comma = true
  643. key.escapeJson(result)
  644. result.add ":"
  645. result.toUgly value
  646. result.add "}"
  647. of JString:
  648. if node.isUnquoted:
  649. result.add node.str
  650. else:
  651. escapeJson(node.str, result)
  652. of JInt:
  653. result.addInt(node.num)
  654. of JFloat:
  655. result.addFloat(node.fnum)
  656. of JBool:
  657. result.add(if node.bval: "true" else: "false")
  658. of JNull:
  659. result.add "null"
  660. proc toPretty(result: var string, node: JsonNode, indent = 2, ml = true,
  661. lstArr = false, currIndent = 0) =
  662. case node.kind
  663. of JObject:
  664. if lstArr: result.indent(currIndent) # Indentation
  665. if node.fields.len > 0:
  666. result.add("{")
  667. result.nl(ml) # New line
  668. var i = 0
  669. for key, val in pairs(node.fields):
  670. if i > 0:
  671. result.add(",")
  672. result.nl(ml) # New Line
  673. inc i
  674. # Need to indent more than {
  675. result.indent(newIndent(currIndent, indent, ml))
  676. escapeJson(key, result)
  677. result.add(": ")
  678. toPretty(result, val, indent, ml, false,
  679. newIndent(currIndent, indent, ml))
  680. result.nl(ml)
  681. result.indent(currIndent) # indent the same as {
  682. result.add("}")
  683. else:
  684. result.add("{}")
  685. of JString:
  686. if lstArr: result.indent(currIndent)
  687. toUgly(result, node)
  688. of JInt:
  689. if lstArr: result.indent(currIndent)
  690. result.addInt(node.num)
  691. of JFloat:
  692. if lstArr: result.indent(currIndent)
  693. result.addFloat(node.fnum)
  694. of JBool:
  695. if lstArr: result.indent(currIndent)
  696. result.add(if node.bval: "true" else: "false")
  697. of JArray:
  698. if lstArr: result.indent(currIndent)
  699. if len(node.elems) != 0:
  700. result.add("[")
  701. result.nl(ml)
  702. for i in 0..len(node.elems)-1:
  703. if i > 0:
  704. result.add(",")
  705. result.nl(ml) # New Line
  706. toPretty(result, node.elems[i], indent, ml,
  707. true, newIndent(currIndent, indent, ml))
  708. result.nl(ml)
  709. result.indent(currIndent)
  710. result.add("]")
  711. else: result.add("[]")
  712. of JNull:
  713. if lstArr: result.indent(currIndent)
  714. result.add("null")
  715. proc pretty*(node: JsonNode, indent = 2): string =
  716. ## Returns a JSON Representation of `node`, with indentation and
  717. ## on multiple lines.
  718. ##
  719. ## Similar to prettyprint in Python.
  720. runnableExamples:
  721. let j = %* {"name": "Isaac", "books": ["Robot Dreams"],
  722. "details": {"age": 35, "pi": 3.1415}}
  723. doAssert pretty(j) == """
  724. {
  725. "name": "Isaac",
  726. "books": [
  727. "Robot Dreams"
  728. ],
  729. "details": {
  730. "age": 35,
  731. "pi": 3.1415
  732. }
  733. }"""
  734. result = ""
  735. toPretty(result, node, indent)
  736. proc `$`*(node: JsonNode): string =
  737. ## Converts `node` to its JSON Representation on one line.
  738. result = newStringOfCap(node.len shl 1)
  739. toUgly(result, node)
  740. iterator items*(node: JsonNode): JsonNode =
  741. ## Iterator for the items of `node`. `node` has to be a JArray.
  742. assert node.kind == JArray, ": items() can not iterate a JsonNode of kind " & $node.kind
  743. for i in items(node.elems):
  744. yield i
  745. iterator mitems*(node: var JsonNode): var JsonNode =
  746. ## Iterator for the items of `node`. `node` has to be a JArray. Items can be
  747. ## modified.
  748. assert node.kind == JArray, ": mitems() can not iterate a JsonNode of kind " & $node.kind
  749. for i in mitems(node.elems):
  750. yield i
  751. iterator pairs*(node: JsonNode): tuple[key: string, val: JsonNode] =
  752. ## Iterator for the child elements of `node`. `node` has to be a JObject.
  753. assert node.kind == JObject, ": pairs() can not iterate a JsonNode of kind " & $node.kind
  754. for key, val in pairs(node.fields):
  755. yield (key, val)
  756. iterator keys*(node: JsonNode): string =
  757. ## Iterator for the keys in `node`. `node` has to be a JObject.
  758. assert node.kind == JObject, ": keys() can not iterate a JsonNode of kind " & $node.kind
  759. for key in node.fields.keys:
  760. yield key
  761. iterator mpairs*(node: var JsonNode): tuple[key: string, val: var JsonNode] =
  762. ## Iterator for the child elements of `node`. `node` has to be a JObject.
  763. ## Values can be modified
  764. assert node.kind == JObject, ": mpairs() can not iterate a JsonNode of kind " & $node.kind
  765. for key, val in mpairs(node.fields):
  766. yield (key, val)
  767. proc parseJson(p: var JsonParser; rawIntegers, rawFloats: bool, depth = 0): JsonNode =
  768. ## Parses JSON from a JSON Parser `p`.
  769. case p.tok
  770. of tkString:
  771. # we capture 'p.a' here, so we need to give it a fresh buffer afterwards:
  772. when defined(gcArc) or defined(gcOrc):
  773. result = JsonNode(kind: JString, str: move p.a)
  774. else:
  775. result = JsonNode(kind: JString)
  776. shallowCopy(result.str, p.a)
  777. p.a = ""
  778. discard getTok(p)
  779. of tkInt:
  780. if rawIntegers:
  781. result = newJRawNumber(p.a)
  782. else:
  783. try:
  784. result = newJInt(parseBiggestInt(p.a))
  785. except ValueError:
  786. result = newJRawNumber(p.a)
  787. discard getTok(p)
  788. of tkFloat:
  789. if rawFloats:
  790. result = newJRawNumber(p.a)
  791. else:
  792. try:
  793. result = newJFloat(parseFloat(p.a))
  794. except ValueError:
  795. result = newJRawNumber(p.a)
  796. discard getTok(p)
  797. of tkTrue:
  798. result = newJBool(true)
  799. discard getTok(p)
  800. of tkFalse:
  801. result = newJBool(false)
  802. discard getTok(p)
  803. of tkNull:
  804. result = newJNull()
  805. discard getTok(p)
  806. of tkCurlyLe:
  807. if depth > DepthLimit:
  808. raiseParseErr(p, "}")
  809. result = newJObject()
  810. discard getTok(p)
  811. while p.tok != tkCurlyRi:
  812. if p.tok != tkString:
  813. raiseParseErr(p, "string literal as key")
  814. var key = p.a
  815. discard getTok(p)
  816. eat(p, tkColon)
  817. var val = parseJson(p, rawIntegers, rawFloats, depth+1)
  818. result[key] = val
  819. if p.tok != tkComma: break
  820. discard getTok(p)
  821. eat(p, tkCurlyRi)
  822. of tkBracketLe:
  823. if depth > DepthLimit:
  824. raiseParseErr(p, "]")
  825. result = newJArray()
  826. discard getTok(p)
  827. while p.tok != tkBracketRi:
  828. result.add(parseJson(p, rawIntegers, rawFloats, depth+1))
  829. if p.tok != tkComma: break
  830. discard getTok(p)
  831. eat(p, tkBracketRi)
  832. of tkError, tkCurlyRi, tkBracketRi, tkColon, tkComma, tkEof:
  833. raiseParseErr(p, "{")
  834. iterator parseJsonFragments*(s: Stream, filename: string = ""; rawIntegers = false, rawFloats = false): JsonNode =
  835. ## Parses from a stream `s` into `JsonNodes`. `filename` is only needed
  836. ## for nice error messages.
  837. ## The JSON fragments are separated by whitespace. This can be substantially
  838. ## faster than the comparable loop
  839. ## `for x in splitWhitespace(s): yield parseJson(x)`.
  840. ## This closes the stream `s` after it's done.
  841. ## If `rawIntegers` is true, integer literals will not be converted to a `JInt`
  842. ## field but kept as raw numbers via `JString`.
  843. ## If `rawFloats` is true, floating point literals will not be converted to a `JFloat`
  844. ## field but kept as raw numbers via `JString`.
  845. var p: JsonParser
  846. p.open(s, filename)
  847. try:
  848. discard getTok(p) # read first token
  849. while p.tok != tkEof:
  850. yield p.parseJson(rawIntegers, rawFloats)
  851. finally:
  852. p.close()
  853. proc parseJson*(s: Stream, filename: string = ""; rawIntegers = false, rawFloats = false): JsonNode =
  854. ## Parses from a stream `s` into a `JsonNode`. `filename` is only needed
  855. ## for nice error messages.
  856. ## If `s` contains extra data, it will raise `JsonParsingError`.
  857. ## This closes the stream `s` after it's done.
  858. ## If `rawIntegers` is true, integer literals will not be converted to a `JInt`
  859. ## field but kept as raw numbers via `JString`.
  860. ## If `rawFloats` is true, floating point literals will not be converted to a `JFloat`
  861. ## field but kept as raw numbers via `JString`.
  862. var p: JsonParser
  863. p.open(s, filename)
  864. try:
  865. discard getTok(p) # read first token
  866. result = p.parseJson(rawIntegers, rawFloats)
  867. eat(p, tkEof) # check if there is no extra data
  868. finally:
  869. p.close()
  870. when defined(js):
  871. from math import `mod`
  872. from std/jsffi import JsObject, `[]`, to
  873. from std/private/jsutils import getProtoName, isInteger, isSafeInteger
  874. proc parseNativeJson(x: cstring): JsObject {.importjs: "JSON.parse(#)".}
  875. proc getVarType(x: JsObject, isRawNumber: var bool): JsonNodeKind =
  876. result = JNull
  877. case $getProtoName(x) # TODO: Implicit returns fail here.
  878. of "[object Array]": return JArray
  879. of "[object Object]": return JObject
  880. of "[object Number]":
  881. if isInteger(x) and 1.0 / cast[float](x) != -Inf: # preserve -0.0 as float
  882. if isSafeInteger(x):
  883. return JInt
  884. else:
  885. isRawNumber = true
  886. return JString
  887. else:
  888. return JFloat
  889. of "[object Boolean]": return JBool
  890. of "[object Null]": return JNull
  891. of "[object String]": return JString
  892. else: assert false
  893. proc len(x: JsObject): int =
  894. asm """
  895. `result` = `x`.length;
  896. """
  897. proc convertObject(x: JsObject): JsonNode =
  898. var isRawNumber = false
  899. case getVarType(x, isRawNumber)
  900. of JArray:
  901. result = newJArray()
  902. for i in 0 ..< x.len:
  903. result.add(x[i].convertObject())
  904. of JObject:
  905. result = newJObject()
  906. asm """for (var property in `x`) {
  907. if (`x`.hasOwnProperty(property)) {
  908. """
  909. var nimProperty: cstring
  910. var nimValue: JsObject
  911. asm "`nimProperty` = property; `nimValue` = `x`[property];"
  912. result[$nimProperty] = nimValue.convertObject()
  913. asm "}}"
  914. of JInt:
  915. result = newJInt(x.to(int))
  916. of JFloat:
  917. result = newJFloat(x.to(float))
  918. of JString:
  919. # Dunno what to do with isUnquoted here
  920. if isRawNumber:
  921. var value: cstring
  922. {.emit: "`value` = `x`.toString();".}
  923. result = newJRawNumber($value)
  924. else:
  925. result = newJString($x.to(cstring))
  926. of JBool:
  927. result = newJBool(x.to(bool))
  928. of JNull:
  929. result = newJNull()
  930. proc parseJson*(buffer: string): JsonNode =
  931. when nimvm:
  932. return parseJson(newStringStream(buffer), "input")
  933. else:
  934. return parseNativeJson(buffer).convertObject()
  935. else:
  936. proc parseJson*(buffer: string; rawIntegers = false, rawFloats = false): JsonNode =
  937. ## Parses JSON from `buffer`.
  938. ## If `buffer` contains extra data, it will raise `JsonParsingError`.
  939. ## If `rawIntegers` is true, integer literals will not be converted to a `JInt`
  940. ## field but kept as raw numbers via `JString`.
  941. ## If `rawFloats` is true, floating point literals will not be converted to a `JFloat`
  942. ## field but kept as raw numbers via `JString`.
  943. result = parseJson(newStringStream(buffer), "input", rawIntegers, rawFloats)
  944. proc parseFile*(filename: string): JsonNode =
  945. ## Parses `file` into a `JsonNode`.
  946. ## If `file` contains extra data, it will raise `JsonParsingError`.
  947. var stream = newFileStream(filename, fmRead)
  948. if stream == nil:
  949. raise newException(IOError, "cannot read from file: " & filename)
  950. result = parseJson(stream, filename, rawIntegers=false, rawFloats=false)
  951. # -- Json deserialiser. --
  952. template verifyJsonKind(node: JsonNode, kinds: set[JsonNodeKind],
  953. ast: string) =
  954. if node == nil:
  955. raise newException(KeyError, "key not found: " & ast)
  956. elif node.kind notin kinds:
  957. let msg = "Incorrect JSON kind. Wanted '$1' in '$2' but got '$3'." % [
  958. $kinds,
  959. ast,
  960. $node.kind
  961. ]
  962. raise newException(JsonKindError, msg)
  963. macro isRefSkipDistinct*(arg: typed): untyped =
  964. ## internal only, do not use
  965. var impl = getTypeImpl(arg)
  966. if impl.kind == nnkBracketExpr and impl[0].eqIdent("typeDesc"):
  967. impl = getTypeImpl(impl[1])
  968. while impl.kind == nnkDistinctTy:
  969. impl = getTypeImpl(impl[0])
  970. result = newLit(impl.kind == nnkRefTy)
  971. # The following forward declarations don't work in older versions of Nim
  972. # forward declare all initFromJson
  973. proc initFromJson(dst: var string; jsonNode: JsonNode; jsonPath: var string)
  974. proc initFromJson(dst: var bool; jsonNode: JsonNode; jsonPath: var string)
  975. proc initFromJson(dst: var JsonNode; jsonNode: JsonNode; jsonPath: var string)
  976. proc initFromJson[T: SomeInteger](dst: var T; jsonNode: JsonNode, jsonPath: var string)
  977. proc initFromJson[T: SomeFloat](dst: var T; jsonNode: JsonNode; jsonPath: var string)
  978. proc initFromJson[T: enum](dst: var T; jsonNode: JsonNode; jsonPath: var string)
  979. proc initFromJson[T](dst: var seq[T]; jsonNode: JsonNode; jsonPath: var string)
  980. proc initFromJson[S, T](dst: var array[S, T]; jsonNode: JsonNode; jsonPath: var string)
  981. proc initFromJson[T](dst: var Table[string, T]; jsonNode: JsonNode; jsonPath: var string)
  982. proc initFromJson[T](dst: var OrderedTable[string, T]; jsonNode: JsonNode; jsonPath: var string)
  983. proc initFromJson[T](dst: var ref T; jsonNode: JsonNode; jsonPath: var string)
  984. proc initFromJson[T](dst: var Option[T]; jsonNode: JsonNode; jsonPath: var string)
  985. proc initFromJson[T: distinct](dst: var T; jsonNode: JsonNode; jsonPath: var string)
  986. proc initFromJson[T: object|tuple](dst: var T; jsonNode: JsonNode; jsonPath: var string)
  987. # initFromJson definitions
  988. proc initFromJson(dst: var string; jsonNode: JsonNode; jsonPath: var string) =
  989. verifyJsonKind(jsonNode, {JString, JNull}, jsonPath)
  990. # since strings don't have a nil state anymore, this mapping of
  991. # JNull to the default string is questionable. `none(string)` and
  992. # `some("")` have the same potentional json value `JNull`.
  993. if jsonNode.kind == JNull:
  994. dst = ""
  995. else:
  996. dst = jsonNode.str
  997. proc initFromJson(dst: var bool; jsonNode: JsonNode; jsonPath: var string) =
  998. verifyJsonKind(jsonNode, {JBool}, jsonPath)
  999. dst = jsonNode.bval
  1000. proc initFromJson(dst: var JsonNode; jsonNode: JsonNode; jsonPath: var string) =
  1001. if jsonNode == nil:
  1002. raise newException(KeyError, "key not found: " & jsonPath)
  1003. dst = jsonNode.copy
  1004. proc initFromJson[T: SomeInteger](dst: var T; jsonNode: JsonNode, jsonPath: var string) =
  1005. when T is uint|uint64 or int.sizeof == 4:
  1006. verifyJsonKind(jsonNode, {JInt, JString}, jsonPath)
  1007. case jsonNode.kind
  1008. of JString:
  1009. let x = parseBiggestUInt(jsonNode.str)
  1010. dst = cast[T](x)
  1011. else:
  1012. dst = T(jsonNode.num)
  1013. else:
  1014. verifyJsonKind(jsonNode, {JInt}, jsonPath)
  1015. dst = cast[T](jsonNode.num)
  1016. proc initFromJson[T: SomeFloat](dst: var T; jsonNode: JsonNode; jsonPath: var string) =
  1017. verifyJsonKind(jsonNode, {JInt, JFloat, JString}, jsonPath)
  1018. if jsonNode.kind == JString:
  1019. case jsonNode.str
  1020. of "nan":
  1021. let b = NaN
  1022. dst = T(b)
  1023. # dst = NaN # would fail some tests because range conversions would cause CT error
  1024. # in some cases; but this is not a hot-spot inside this branch and backend can optimize this.
  1025. of "inf":
  1026. let b = Inf
  1027. dst = T(b)
  1028. of "-inf":
  1029. let b = -Inf
  1030. dst = T(b)
  1031. else: raise newException(JsonKindError, "expected 'nan|inf|-inf', got " & jsonNode.str)
  1032. else:
  1033. if jsonNode.kind == JFloat:
  1034. dst = T(jsonNode.fnum)
  1035. else:
  1036. dst = T(jsonNode.num)
  1037. proc initFromJson[T: enum](dst: var T; jsonNode: JsonNode; jsonPath: var string) =
  1038. verifyJsonKind(jsonNode, {JString}, jsonPath)
  1039. dst = parseEnum[T](jsonNode.getStr)
  1040. proc initFromJson[T](dst: var seq[T]; jsonNode: JsonNode; jsonPath: var string) =
  1041. verifyJsonKind(jsonNode, {JArray}, jsonPath)
  1042. dst.setLen jsonNode.len
  1043. let orignalJsonPathLen = jsonPath.len
  1044. for i in 0 ..< jsonNode.len:
  1045. jsonPath.add '['
  1046. jsonPath.addInt i
  1047. jsonPath.add ']'
  1048. initFromJson(dst[i], jsonNode[i], jsonPath)
  1049. jsonPath.setLen orignalJsonPathLen
  1050. proc initFromJson[S,T](dst: var array[S,T]; jsonNode: JsonNode; jsonPath: var string) =
  1051. verifyJsonKind(jsonNode, {JArray}, jsonPath)
  1052. let originalJsonPathLen = jsonPath.len
  1053. for i in 0 ..< jsonNode.len:
  1054. jsonPath.add '['
  1055. jsonPath.addInt i
  1056. jsonPath.add ']'
  1057. initFromJson(dst[i.S], jsonNode[i], jsonPath) # `.S` for enum indexed arrays
  1058. jsonPath.setLen originalJsonPathLen
  1059. proc initFromJson[T](dst: var Table[string,T]; jsonNode: JsonNode; jsonPath: var string) =
  1060. dst = initTable[string, T]()
  1061. verifyJsonKind(jsonNode, {JObject}, jsonPath)
  1062. let originalJsonPathLen = jsonPath.len
  1063. for key in keys(jsonNode.fields):
  1064. jsonPath.add '.'
  1065. jsonPath.add key
  1066. initFromJson(mgetOrPut(dst, key, default(T)), jsonNode[key], jsonPath)
  1067. jsonPath.setLen originalJsonPathLen
  1068. proc initFromJson[T](dst: var OrderedTable[string,T]; jsonNode: JsonNode; jsonPath: var string) =
  1069. dst = initOrderedTable[string,T]()
  1070. verifyJsonKind(jsonNode, {JObject}, jsonPath)
  1071. let originalJsonPathLen = jsonPath.len
  1072. for key in keys(jsonNode.fields):
  1073. jsonPath.add '.'
  1074. jsonPath.add key
  1075. initFromJson(mgetOrPut(dst, key, default(T)), jsonNode[key], jsonPath)
  1076. jsonPath.setLen originalJsonPathLen
  1077. proc initFromJson[T](dst: var ref T; jsonNode: JsonNode; jsonPath: var string) =
  1078. verifyJsonKind(jsonNode, {JObject, JNull}, jsonPath)
  1079. if jsonNode.kind == JNull:
  1080. dst = nil
  1081. else:
  1082. dst = new(T)
  1083. initFromJson(dst[], jsonNode, jsonPath)
  1084. proc initFromJson[T](dst: var Option[T]; jsonNode: JsonNode; jsonPath: var string) =
  1085. if jsonNode != nil and jsonNode.kind != JNull:
  1086. when T is ref:
  1087. dst = some(new(T))
  1088. else:
  1089. dst = some(default(T))
  1090. initFromJson(dst.get, jsonNode, jsonPath)
  1091. macro assignDistinctImpl[T: distinct](dst: var T;jsonNode: JsonNode; jsonPath: var string) =
  1092. let typInst = getTypeInst(dst)
  1093. let typImpl = getTypeImpl(dst)
  1094. let baseTyp = typImpl[0]
  1095. result = quote do:
  1096. when nimvm:
  1097. # workaround #12282
  1098. var tmp: `baseTyp`
  1099. initFromJson( tmp, `jsonNode`, `jsonPath`)
  1100. `dst` = `typInst`(tmp)
  1101. else:
  1102. initFromJson( `baseTyp`(`dst`), `jsonNode`, `jsonPath`)
  1103. proc initFromJson[T: distinct](dst: var T; jsonNode: JsonNode; jsonPath: var string) =
  1104. assignDistinctImpl(dst, jsonNode, jsonPath)
  1105. proc detectIncompatibleType(typeExpr, lineinfoNode: NimNode) =
  1106. if typeExpr.kind == nnkTupleConstr:
  1107. error("Use a named tuple instead of: " & typeExpr.repr, lineinfoNode)
  1108. proc foldObjectBody(dst, typeNode, tmpSym, jsonNode, jsonPath, originalJsonPathLen: NimNode) =
  1109. case typeNode.kind
  1110. of nnkEmpty:
  1111. discard
  1112. of nnkRecList, nnkTupleTy:
  1113. for it in typeNode:
  1114. foldObjectBody(dst, it, tmpSym, jsonNode, jsonPath, originalJsonPathLen)
  1115. of nnkIdentDefs:
  1116. typeNode.expectLen 3
  1117. let fieldSym = typeNode[0]
  1118. let fieldNameLit = newLit(fieldSym.strVal)
  1119. let fieldPathLit = newLit("." & fieldSym.strVal)
  1120. let fieldType = typeNode[1]
  1121. # Detecting incompatiple tuple types in `assignObjectImpl` only
  1122. # would be much cleaner, but the ast for tuple types does not
  1123. # contain usable type information.
  1124. detectIncompatibleType(fieldType, fieldSym)
  1125. dst.add quote do:
  1126. jsonPath.add `fieldPathLit`
  1127. when nimvm:
  1128. when isRefSkipDistinct(`tmpSym`.`fieldSym`):
  1129. # workaround #12489
  1130. var tmp: `fieldType`
  1131. initFromJson(tmp, getOrDefault(`jsonNode`,`fieldNameLit`), `jsonPath`)
  1132. `tmpSym`.`fieldSym` = tmp
  1133. else:
  1134. initFromJson(`tmpSym`.`fieldSym`, getOrDefault(`jsonNode`,`fieldNameLit`), `jsonPath`)
  1135. else:
  1136. initFromJson(`tmpSym`.`fieldSym`, getOrDefault(`jsonNode`,`fieldNameLit`), `jsonPath`)
  1137. jsonPath.setLen `originalJsonPathLen`
  1138. of nnkRecCase:
  1139. let kindSym = typeNode[0][0]
  1140. let kindNameLit = newLit(kindSym.strVal)
  1141. let kindPathLit = newLit("." & kindSym.strVal)
  1142. let kindType = typeNode[0][1]
  1143. let kindOffsetLit = newLit(uint(getOffset(kindSym)))
  1144. dst.add quote do:
  1145. var kindTmp: `kindType`
  1146. jsonPath.add `kindPathLit`
  1147. initFromJson(kindTmp, `jsonNode`[`kindNameLit`], `jsonPath`)
  1148. jsonPath.setLen `originalJsonPathLen`
  1149. when defined js:
  1150. `tmpSym`.`kindSym` = kindTmp
  1151. else:
  1152. when nimvm:
  1153. `tmpSym`.`kindSym` = kindTmp
  1154. else:
  1155. # fuck it, assign kind field anyway
  1156. ((cast[ptr `kindType`](cast[uint](`tmpSym`.addr) + `kindOffsetLit`))[]) = kindTmp
  1157. dst.add nnkCaseStmt.newTree(nnkDotExpr.newTree(tmpSym, kindSym))
  1158. for i in 1 ..< typeNode.len:
  1159. foldObjectBody(dst, typeNode[i], tmpSym, jsonNode, jsonPath, originalJsonPathLen)
  1160. of nnkOfBranch, nnkElse:
  1161. let ofBranch = newNimNode(typeNode.kind)
  1162. for i in 0 ..< typeNode.len-1:
  1163. ofBranch.add copyNimTree(typeNode[i])
  1164. let dstInner = newNimNode(nnkStmtListExpr)
  1165. foldObjectBody(dstInner, typeNode[^1], tmpSym, jsonNode, jsonPath, originalJsonPathLen)
  1166. # resOuter now contains the inner stmtList
  1167. ofBranch.add dstInner
  1168. dst[^1].expectKind nnkCaseStmt
  1169. dst[^1].add ofBranch
  1170. of nnkObjectTy:
  1171. typeNode[0].expectKind nnkEmpty
  1172. typeNode[1].expectKind {nnkEmpty, nnkOfInherit}
  1173. if typeNode[1].kind == nnkOfInherit:
  1174. let base = typeNode[1][0]
  1175. var impl = getTypeImpl(base)
  1176. while impl.kind in {nnkRefTy, nnkPtrTy}:
  1177. impl = getTypeImpl(impl[0])
  1178. foldObjectBody(dst, impl, tmpSym, jsonNode, jsonPath, originalJsonPathLen)
  1179. let body = typeNode[2]
  1180. foldObjectBody(dst, body, tmpSym, jsonNode, jsonPath, originalJsonPathLen)
  1181. else:
  1182. error("unhandled kind: " & $typeNode.kind, typeNode)
  1183. macro assignObjectImpl[T](dst: var T; jsonNode: JsonNode; jsonPath: var string) =
  1184. let typeSym = getTypeInst(dst)
  1185. let originalJsonPathLen = genSym(nskLet, "originalJsonPathLen")
  1186. result = newStmtList()
  1187. result.add quote do:
  1188. let `originalJsonPathLen` = len(`jsonPath`)
  1189. if typeSym.kind in {nnkTupleTy, nnkTupleConstr}:
  1190. # both, `dst` and `typeSym` don't have good lineinfo. But nothing
  1191. # else is available here.
  1192. detectIncompatibleType(typeSym, dst)
  1193. foldObjectBody(result, typeSym, dst, jsonNode, jsonPath, originalJsonPathLen)
  1194. else:
  1195. foldObjectBody(result, typeSym.getTypeImpl, dst, jsonNode, jsonPath, originalJsonPathLen)
  1196. proc initFromJson[T: object|tuple](dst: var T; jsonNode: JsonNode; jsonPath: var string) =
  1197. assignObjectImpl(dst, jsonNode, jsonPath)
  1198. proc to*[T](node: JsonNode, t: typedesc[T]): T =
  1199. ## `Unmarshals`:idx: the specified node into the object type specified.
  1200. ##
  1201. ## Known limitations:
  1202. ##
  1203. ## * Heterogeneous arrays are not supported.
  1204. ## * Sets in object variants are not supported.
  1205. ## * Not nil annotations are not supported.
  1206. ##
  1207. runnableExamples:
  1208. let jsonNode = parseJson("""
  1209. {
  1210. "person": {
  1211. "name": "Nimmer",
  1212. "age": 21
  1213. },
  1214. "list": [1, 2, 3, 4]
  1215. }
  1216. """)
  1217. type
  1218. Person = object
  1219. name: string
  1220. age: int
  1221. Data = object
  1222. person: Person
  1223. list: seq[int]
  1224. var data = to(jsonNode, Data)
  1225. doAssert data.person.name == "Nimmer"
  1226. doAssert data.person.age == 21
  1227. doAssert data.list == @[1, 2, 3, 4]
  1228. var jsonPath = ""
  1229. result = default(T)
  1230. initFromJson(result, node, jsonPath)
  1231. when false:
  1232. import os
  1233. var s = newFileStream(paramStr(1), fmRead)
  1234. if s == nil: quit("cannot open the file" & paramStr(1))
  1235. var x: JsonParser
  1236. open(x, s, paramStr(1))
  1237. while true:
  1238. next(x)
  1239. case x.kind
  1240. of jsonError:
  1241. Echo(x.errorMsg())
  1242. break
  1243. of jsonEof: break
  1244. of jsonString, jsonInt, jsonFloat: echo(x.str)
  1245. of jsonTrue: echo("!TRUE")
  1246. of jsonFalse: echo("!FALSE")
  1247. of jsonNull: echo("!NULL")
  1248. of jsonObjectStart: echo("{")
  1249. of jsonObjectEnd: echo("}")
  1250. of jsonArrayStart: echo("[")
  1251. of jsonArrayEnd: echo("]")
  1252. close(x)
  1253. # { "json": 5 }
  1254. # To get that we shall use, obj["json"]