Nim: How to parse JSON

Mar 21, 2022

To parse a JSON string into an object, use the json import from the standard library:

import json

let jsonObject = """{"first_name": "glenn", "last_name": "gillen"}"""
let jsonArray = """[7, 8, 9]"""

let parsedObject = parseJson(jsonObject)
let parsedArray = parseJson(jsonArray)

This will create a series of nodes, on which you'll need to call getStr(), getInt(), getFloat(), or getBool() to retrieve the actual value:

ech parsedObject["first_name"].getStr() # glenn
echo parsedArray[1].getInt() # 8

If you've a nested JSON object Nim will automatically parse the nesting and you'll only need to call the get*() on the edge node:

import json
let jsonObject = """{
  "names": {
    "first": "glenn",
    "last": "gillen"
  }
}"""
let parsedObject = parseJson(jsonObject)
echo parsedObject["names"]["first"].getStr() # glenn

To parse into an object, you'll need to define an object that matches your expected structure:

import json

type
  Person = object
    first_name: string
    last_name: string

let jsonObject = parseJson("""{"first_name": "glenn", "last_name": "gillen"}""")
let person = to(jsonObject, Person)

echo person.first_name # glenn
Hi, I'm Glenn! 👋 I'm currently Director of Product (Terraform) @ HashiCorp, and we're hiring! If you'd like to come and work with me and help make Terraform Cloud even more amazing we have multiple positions opening in Product ManagementDesign, and Engineering & Engineering Management across a range of levels (i.e., junior through to senior). Please send in an application ASAP so we can get in touch.