summary refs log tree commit diff stats
path: root/lib/pure/json.nim
diff options
context:
space:
mode:
Diffstat (limited to 'lib/pure/json.nim')
-rwxr-xr-xlib/pure/json.nim32
1 files changed, 30 insertions, 2 deletions
diff --git a/lib/pure/json.nim b/lib/pure/json.nim
index 941d88dfc..d2516adfb 100755
--- a/lib/pure/json.nim
+++ b/lib/pure/json.nim
@@ -13,6 +13,23 @@
 ## (unlike XML). It is easy for machines to parse and generate.
 ## JSON is based on a subset of the JavaScript Programming Language,
 ## Standard ECMA-262 3rd Edition - December 1999.
+##
+## Usage example:
+##
+## .. code-block:: nimrod
+##  let
+##    small_json = """{"test": 1.3, "key2": true}"""
+##    jobj = parseJson(small_json)
+##  assert (jobj.kind == JObject)
+##  echo($jobj["test"].fnum)
+##  echo($jobj["key2"].bval)
+##
+## Results in:
+##
+## .. code-block:: nimrod
+##
+##   1.3000000000000000e+00
+##   true
 
 import 
   hashes, strutils, lexbase, streams, unicode
@@ -524,6 +541,11 @@ proc newJString*(s: String): PJsonNode =
   result.kind = JString
   result.str = s
 
+proc newJStringMove(s: String): PJsonNode =
+  new(result)
+  result.kind = JString
+  shallowCopy(result.str, s)
+
 proc newJInt*(n: biggestInt): PJsonNode =
   ## Creates a new `JInt PJsonNode`.
   new(result)
@@ -607,7 +629,7 @@ proc len*(n: PJsonNode): int =
   else: nil
 
 proc `[]`*(node: PJsonNode, name: String): PJsonNode =
-  ## Gets a field from a `JObject`.
+  ## Gets a field from a `JObject`. Returns nil if the key is not found.
   assert(node.kind == JObject)
   for key, item in items(node.fields):
     if key == name:
@@ -792,7 +814,9 @@ proc parseJson(p: var TJsonParser): PJsonNode =
   ## Parses JSON from a JSON Parser `p`.
   case p.tok
   of tkString:
-    result = newJString(p.a)
+    # we capture 'p.a' here, so we need to give it a fresh buffer afterwards:
+    result = newJStringMove(p.a)
+    p.a = ""
     discard getTok(p)
   of tkInt:
     result = newJInt(parseBiggestInt(p.a))
@@ -893,6 +917,10 @@ when isMainModule:
   echo(parsed["keyÄÖöoßß"])
   echo()
   echo(pretty(parsed2))
+  try:
+    echo(parsed["key2"][12123])
+    raise newException(EInvalidValue, "That line was expected to fail")
+  except EInvalidIndex: echo()
 
   discard """
   while true: