Nim example - Convert JSOn to/from the object
This tutorial shows NIM object and json string object conversion examples
$$
: to serialize Nim Object to JSOn string.to
: deserialize json string to Nim Object
How to convert Nim Object to JSOn
Nim has a marshal
module that contains the procedure to serialize and deserialize data from NIM objects. $$
is used to convert Nim Object to JSOn string.
Here is an example
- Create an Employee object
- Variable created by adding data using the constructor
- $$variable returns the JSOn string
import std/marshal
type
Employee = object
id: int
name: string
var emp = Employee(id: 1, name: "john")
echo($$emp)
echo(typeOf($$emp))
Output:
{"id": 1, "name": "john"}
How to Convert JSON string into Nim Object
JSON string is declared with string literal with triple quote syntax. triple quotes are used for declaring long forms of strings.
The marshal
module contains a to
procedure that converts a string to Nim Object.
Here is an example
import std/marshal
type
Employee = object
id: int
name: string
var emp = Employee(id: 1, name: "john")
let jsonString = """{"id": 1, "name": "eric"}"""
let nimObject = jsonString.to[:Employee]
echo(nimObject)
echo(typeOf(nimObject))
Output:
(id: 1, name: "eric")
Employee