Nim supports the JSON format natively, it's in the standard library.
Read a list of numbers
Say we have a file that contains a list of integers. The task is the following: read it into a seq[int].
short.json :
[171, 190, 180, 193, 180]
Ver. 1: parseFile()
import std/strutils # strip, split, join
import std/json
proc main() =
let
parsed: JsonNode = parseFile("short.json")
numbers: seq[int] = parsed.to(seq[int])
echo numbers # @[171, 190, 180, 193, 180]
main()
A JsonNode is Nim's universal JSON value type — it can hold any JSON value. We specify the filename, its content is read to a universal JSON type, which is parsed to a specific Nim type, namely to seq[int].
Ver. 2: readFile()
Let's see how to convert a JSON string to a native Nim type.
Suppose we've already read the content of a JSON file and we have the content as a string. Thus, having a JSON string, how to convert it to a native Nim type?
import std/strutils # strip, split, join
import std/json
proc main() =
let
content: string = readFile("short.json")
parsed: JsonNode = parseJson(content)
numbers: seq[int] = parsed.to(seq[int])
echo numbers # @[171, 190, 180, 193, 180]
main()
We could also simplify it to two lines:
let
content: string = readFile("short.json")
numbers: seq[int] = parseJson(content).to(seq[int])