Nim: How to parse nested JSON into objects

Mar 22, 2022

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
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.