encode
Writing types of your own as JSON
An encoder writes a value of your own type as a Json value, the other way from the
decoders. json.encode writes a value as JSON text by one.
::dependency nanyx.json 0.1.0
import (
nanyx.json/encode as encode
nanyx.json/json as json
)
type User = (name: string, age: int, nickname: #some(string) | #none)
def user: json.Encoder(User) = encode.object(
[
encode.field("name", { u -> u.name }, encode.string)
encode.field("age", { u -> u.age }, encode.int)
encode.optionalField("nickname", { u -> u.nickname }, encode.string)
]
)
println(json.encode(User(name = "Ada", age = 36, nickname = #none), user))
-- {"name":"Ada","age":36}
Reference
Encoders: a value of a type of your own written as JSON, the other way from json’s decoders.
An Encoder(a) is a function from an a to a Json value, so any such
function is one. The encoders here write one kind of value each (string, int,
float, bool), and the rest build larger ones from smaller: list, dict,
optional, and object, which writes a record a member at a time, each a field or an
optionalField. json.encode writes a value as JSON text by an encoder.
type User = (name: string, age: int)
def user: json.Encoder(User) = encode.object(
[
encode.field("name", { u -> u.name }, encode.string)
encode.field("age", { u -> u.age }, encode.int)
]
)
json.encode(User(name = "Ada", age = 36), user)
The encoders are in a module of their own, nanyx.json/encode, imported as encode, since their
names are the decoders’ in nanyx.json/json.
string
def string: Encoder(string)
Writes a string.
int
def int: Encoder(int)
Writes an int as a number.
float
def float: Encoder(float)
Writes a float as a number. NaN and infinity, which JSON can’t write, are printed as null.
bool
def bool: Encoder(bool)
Writes true or false.
list
def list: Encoder(a) -> Encoder(list(a))
Writes a list as an array, each element by encoder.
dict
def dict: Encoder(a) -> Encoder(map(string, a))
Writes a map as an object, each value by encoder, in the map’s order.
optional
def optional: Encoder(a) -> Encoder(#some(a) | #none)
Writes #none as null, and #some(x) as encoder writes x.
Member
type Member(a) = private (name: string, write: (a -> #some(Json) | #none))
A member of an object that object writes for a value of type a: its name, and its value,
or none, for a member that is left out.
field
def field: string, (a -> b), Encoder(b) -> Member(a)
The member name, whose value is encoder of get of the value: encode.field("age", { u -> u.age }, encode.int).
optionalField
def optionalField: string, (a -> #some(b) | #none), Encoder(b) -> Member(a)
The member name, written as field writes one when get gives #some, and left out when
it gives #none: for an optional member, which optional would write as null instead.
object
def object: list(Member(a)) -> Encoder(a)
Writes a value as an object of members, in their order.