This tutorial explains JSON examples in the Nim language

JSON contains key and value pairs where the value can be simple primitive values or arrays or objects.

Declare JSON string in nim

JSON object declared using %* with key and value pairs enclosed in {}.

json module needs to be imported into the code

import json

let jsonObj = %* {"id": 1, "name": "john"}
echo jsonObj

Output:

{"id":1, "name": "john"}

How to parse JSON String in Nim

JSON string variables are created and assigned with JSON string using triple quotes("""). The parseJson method takes the json String and converts it into the JsonNode object. Attributes are read from A JsonNode object using a square bracket with the attribute name and call the getStr() method for string fields, and the getInt() method for number fields.

getInt(), getFloat(), getStr(), and getBool() are methods in the JsonNode object to convert the attribute datatype. Here is an example

import json

let jsonString = """{"id": 1, "name": "john"}"""
echo jsonString
let jsonObject = parseJson(jsonString)
let name = jsonObject["name"].getStr()
echo name

How to Convert JSON into Nim Object

Sometimes, You have a JSOn object that needs to convert to a NIm object.

Nim object created using type with required fields matched with json fields

The to method takes json objects and NIM objects and converts them into a Nim object.

let obj = to(jsonObject, Employee)

Here is an example

import json

let jsonString = """{"id": 1, "name": "john"}"""
echo jsonString
let jsonObject = parseJson(jsonString)

type
  Employee = object
    id: int
    name: string

let obj = to(jsonObject, Employee)
echo obj.name # john
echo obj.id # 1