Skip to content

Instantly share code, notes, and snippets.

@nervecenter
Last active May 24, 2023 14:52
Show Gist options
  • Select an option

  • Save nervecenter/bae5fe9099f40c26c1b56b7a8a8d2efe to your computer and use it in GitHub Desktop.

Select an option

Save nervecenter/bae5fe9099f40c26c1b56b7a8a8d2efe to your computer and use it in GitHub Desktop.
Generic Nim code for querying JSON values, including deeply nested values. Statically typed by way of a default fallback value should the key not be found or be of incorrect type.
# Inputs:
# node: The JsonNode that represents the object you're querying.
# key/keys: The key you're looking for, or the sequence of key steps if your value is deeply nested.
# default: The default value should the key not be found.
# Examples:
# let enable_raytracing: bool = settings_json_node.get_json_value("enable_raytracing", false)
# let enable_raytracing: bool = settings_json_node.get_json_value(@["settings", "graphics", "enable_raytracing"], false)
proc get_json_value*[T: bool | float | int | string | JsonNode](node: JsonNode, keys: seq[string], default: T): T =
var current_node = node
for key in keys:
if key in current_node:
current_node = current_node[key]
else:
return default
when T is bool:
if current_node.kind == JBool:
return current_node.get_bool
when T is float:
if current_node.kind == JFloat or current_node.kind == JInt:
return current_node.get_float
when T is int:
if current_node.kind == JInt:
return current_node.get_int
when T is string:
if current_node.kind == JString:
return current_node.get_str
when T is JsonNode:
if current_node.kind == JObject:
return current_node
return default
proc get_json_value*[T: bool | float | int | string | JsonNode](node: JsonNode, key: string, default: T): T =
node.get_json_value(@[key], default)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment