Documents json [] accesors, raises explicit exception.

This commit is contained in:
Grzegorz Adam Hankiewicz 2012-12-11 21:51:03 +01:00
commit d9dab30c14

View file

@ -607,14 +607,14 @@ proc len*(n: PJsonNode): int =
else: nil else: nil
proc `[]`*(node: PJsonNode, name: String): PJsonNode = 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) assert(node.kind == JObject)
for key, item in items(node.fields): for key, item in items(node.fields):
if key == name: if key == name:
return item return item
return nil return nil
proc `[]`*(node: PJsonNode, index: Int): PJsonNode = proc `[]`*(node: PJsonNode, index: Int): PJsonNode {.raises: [EInvalidIndex].} =
## Gets the node at `index` in an Array. ## Gets the node at `index` in an Array.
assert(node.kind == JArray) assert(node.kind == JArray)
return node.elems[index] return node.elems[index]
@ -893,6 +893,10 @@ when isMainModule:
echo(parsed["keyÄÖöoßß"]) echo(parsed["keyÄÖöoßß"])
echo() echo()
echo(pretty(parsed2)) echo(pretty(parsed2))
try:
echo(parsed["key2"][12123])
raise newException(EInvalidValue, "That line was expected to fail")
except EInvalidIndex: echo()
discard """ discard """
while true: while true: