Nim: How to parse nested JSON into objects

Nim: How to parse nested JSON into objects

Nim will automatically handle recursive parsing of a JSON string into its constituent parts. If itโ€™s a nested object with specific types it can handle that too:

import json

type
  Address = object
    line: string
    state: string
    country: string

  Person = object
    first_name: string
    last_name: string
    address: Address

let jsonObject = parseJson("""{
  "first_name": "glenn",
  "last_name": "gillen",
  "address": {
    "line": "123 Main St",
    "state": "VIC",
    "country": "AU"
  }
}""")
let person = to(jsonObject, Person)

echo person.first_name # glenn
echo person.address.state # VIC

Published:

Hi, I'm Glenn! ๐Ÿ‘‹

I've spent most of my career working with or at startups. You'll usually find me working in Product leadership roles, on an advisory board, or maybe as an early investor.

I've been the VP of Product & GTM @ Ockam. 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.