Nim: How to parse JSON

Nim: How to parse JSON

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

Published: 21/03/2022

Hi, I'm Glenn! 👋

I've spent most of my career working with or at startups. I'm currently the VP of Product / GTM @ Ockam where I'm helping developers build applications and systems that are secure-by-design. It's time we started securely connecting apps, not networks.

Previously I led the Terraform product team @ HashiCorp, where we launched Terraform 1.0, Terraform Cloud, and a whole host of amazing capabilities that set the stage for a successful IPO. Prior to that I was part of the Startup Team @ AWS, and earlier still an early employee @ Heroku. I've also invested in a couple of dozen early stage startups.