Samson is a library for serializing and deserializing JSON5, a superset of JSON. This library is still a work in progress and some features are missing.
The main API consists of only two procs: toJson5
and fromJson5
.
import samson
type User = object
name: string
age: range[0..high(int)]
timezone: Option[string]
let input = """
[
{"name": "John Doe", age: 25},
{"name": "Jane Doe", age: 22, timezone: "Europe/Stockholm"}
]
"""
let parsed = fromJson5(input, seq[User])
echo parsed
# => @[(name: "John Doe", age: 25, timezone: None[string]), (name: "Jane Doe", age: 22, timezone: Some("Europe/Stockholm"))]
echo toJson5(parsed)
# => [{"name": "John Doe", age: 25, timezone: null}, {"name": "Jane Doe", age: 22, timezone: "Europe/Stockholm"}]
Pragma annotations can be used to control how an object type is serialized and deserialized. These are defined and documented in the samson / pragmas
module.
import std/times, samson, samson/pragmas
type Advanced = object
nimField {.jsonFieldName: "jsonField".}: int
hidden {.jsonExclude.}: int
date {.jsonDateTimeFormat: "yyyy-MM-dd".}: DateTime
let x = Advanced(
nimField: 1,
hidden: 2,
date: initDateTime(1, mJan, 2010, 12, 00, 00, utc())
)
echo toJson5(x)
# => {"jsonField": 1, date: "2010-01-01"}
The following types in the standard library have special support in Samson:
int8
,int16
,int32
,int
, andint64
uint8
,uint16
, anduint32
(note:uint
anduint64
are not supported for now)float32
andfloat64
string
char
enum
seq
array
bool
range
(with range checking)options.Option
(maps tonull
when empty)times.Time
times.DateTime
tables.Table
andtables.OrderedTable
(maps to object)set
,sets.HashSet
, andsets.OrderedSet
Samson also supports custom object
(mapped to objects in JSON5) and tuple
(mapped to arrays in JSON5) types.
- Stream based API.
- Support for type variants.
- Support for pretty printing.
- Support for dynamic JSON.
- A strict JSON mode which doesn't support JSON5 features.