Sergio Tapia
Sergio Tapia's Blog

Sergio Tapia's Blog

How to parse a json array with Nim

Sergio Tapia's photo
Sergio Tapia

Published on Aug 9, 2021

Subscribe to my newsletter and never miss my upcoming articles

Given the following JSON, how can you parse it into a nice array to work with in Nim?

[
    {
        "name":"Sergio",
        "favoriteMovie":{
            "title":"Taxi Driver",
            "releaseYear":1976
        }
    },
    {
        "name":"Daniel",
        "favoriteMovie":{
            "title":"Frozen",
            "releaseYear":2013
        }
    }
]

It’s pretty easy, first let’s start by creating the types to marshal the json into.

type
  Movie* = object
    title*: Option[string]
    releaseYear*: Option[int]

type 
  Person* = object
    name*: Option[string]
    favoriteMovie*: Option[Movie]

Then it’s just a matter of parsing the json and using the to function to marshal into a seq[Person].

import json
import strformat
import options

type
  Movie* = object
    title*: Option[string]
    releaseYear*: Option[int]

type 
  Person* = object
    name*: Option[string]
    favoriteMovie*: Option[Movie]

let responseJson = """
[
    {
        "name":"Sergio",
        "favoriteMovie":{
            "title":"Taxi Driver",
            "releaseYear":1976
        }
    },
    {
        "name":"Daniel",
        "favoriteMovie":{
            "title":"Frozen",
            "releaseYear":2013
        }
    }
]
"""

let parsedJson = parseJson(responseJson)
let list = parsedJson.to(seq[Person])
echo $list

The output you’ll see is as expected.

@[(name: Some("Sergio"), favoriteMovie: Some((title: Some("Taxi Driver"), releaseYear: Some(1976)))), (name: Some("Daniel"), favoriteMovie: Some((title: Some("Frozen"), releaseYear: Some(2013))))]
 
Share this