Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert object to json in Nim

Tags:

json

nim-lang

I'm making a small web service in Nim, and I need to respond to requests with json. I'm using the jester module to make the service. I expect I can use the json module in Nim's base library to construct some kind of object with fields and values, and then convert it to a json string. But how? Or is there a better way to construct json in Nim?

like image 654
Torbjørn Avatar asked Oct 04 '14 08:10

Torbjørn


1 Answers

The marshal module includes a generic object-to-json serialisation algorithm that works for any type (currently, it uses run-time type introspection).

import marshal

type
  Person = object
    age: int
    name: string

var p = Person(age: 38, name: "Torbjørn")

echo($$p)

The output will be:

{"age": 38, "name": "Torbj\u00F8rn"}
like image 192
zah Avatar answered Oct 02 '22 15:10

zah