Nim: Object to JSON

Mar 21, 2022

Turning a data structure into JSON is incredibly easy in Nim:

import json

type
  Person = object
    first: string
    last: string

var p = Person(first: "Glenn", last: "Gillen")
echo(%p)

Where the % macro/operator is shorthand from the json module for converting to JSON. There's also the %* macro which can be used for assigning an object directly into a JSON data structure:

import json
let obj = %* { "first_name": "glenn", "last_name": "gillen" }
echo $obj
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.