THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
This tutorial shows NIM object and json string object conversion examples
$$
: to serialize Nim Object to JSOn string.to
: deserialize json string to Nim ObjectNim 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
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"}
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
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts