tobogganSe connecter

packages

The Louise packages, each released on its own

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

NomDernier commitDate
src/packages/json: JSON parsing, writing, ToJson and decoders (ADR 0075)il y a 2 sem.
test/packages/json: JSON parsing, writing, ToJson and decoders (ADR 0075)il y a 2 sem.
CHANGELOG.mdA repository of its own: README, CI, release checks, fixturesil y a 4 j
louise.tomlVersion every package 0.21.0, on louise 0.22.0il y a 4 j
README.mdpackages/json: JSON parsing, writing, ToJson and decoders (ADR 0075)il y a 2 sem.
README.MD

json

JSON (RFC 8259) in pure Louise: a value type, a parser that is safe on untrusted input, a compact and a pretty writer, @derive(ToJson), and decoders that say where a value did not fit.

import json.{type ToJson, Array, Int, Null, Object, String}
import json/decode.{type Decoder}

json.parse "[1, \"two\", null]"          // Ok(Array([Int(1), String("two"), Null]))
json.write (Object([("fuel", Int(80))]))  // "{\"fuel\":80}"
json.pretty value                         // indented by two spaces

@derive ToJson
type Ship { Ship(symbol: String, fuel: Int) }

json.encode (Ship("ORION-1", 80))         // "{\"symbol\":\"ORION-1\",\"fuel\":80}"

Values

pub type Value
{ Null, Bool(Bool), Int(Int), Float(Float), String(String)
, Array(List<Value>), Object(List<(String, Value)>) }
  • A number with no fraction and no exponent is an Int, of any size (Louise's Int promotes to a big integer). Any other number is a Float.
  • An Object keeps its keys in the order they were read or built, so write is deterministic and parse (write v) == Ok(v).
  • json.get value "name" reads one field. For anything more, use a decoder.

Parsing

parse reads a String; parse_bytes reads a request body, which must be UTF-8. Both refuse the following, each with the byte offset (Malformed(at, message)):

  • nesting deeper than max_depth () (512), so a hostile body cannot overflow the stack;
  • a key that appears twice in one object;
  • a malformed or unknown escape, and a lone surrogate ("\uD800");
  • a control character inside a string;
  • a leading zero, .5, 1., +1, Infinity and NaN;
  • a number too large for a Float (1e999), which is refused rather than read as an infinity;
  • anything but whitespace after the value.

Parsing and writing are linear in the input, and a million-element array or a million escapes parse in well under a second natively.

Writing

write produces compact JSON and pretty indents it by two spaces. Both escape ", \ and the control characters, and copy every other character as UTF-8. Writing a Float that is infinite or NaN panics, because JSON has no such number.

@derive(ToJson)

The derive follows the same convention as std/msgpack's ToMsgPack:

LouiseJSON
a record Ship(symbol: "A", fuel: 1){"symbol":"A","fuel":1}
a positional constructor InTransit("B", 30){"InTransit":["B",30]}
a constructor without fields Docked"Docked"
None / Some(x)null / x

Impls are provided for Value, Int, Float, String, Bool, List and Option. When a type's public JSON should differ from its Louise shape (a wire name, a status in snake_case), write the impl by hand.

Decoding

ADR 0019's derives can only consume a value, so decoding is written as decoders, one use line per field:

fn ship :: -> Decoder<Ship>
{
  use symbol <- decode.field "symbol" (decode.string ())
  use fuel <- decode.optional_field "fuel" (decode.int ())
  decode.succeed Ship(symbol, option.unwrap_or fuel 0)
}

decode.from_string body (ship ())
// Error(Mismatch(["route", "1"], "a string", "an integer"))
// shown as: $.route.1: expected a string, found an integer
  • Scalars: string, int, float (which also accepts an integer), bool and value.
  • Containers and fields: list, nullable, field, and optional_field (a missing field or null is None).
  • Combinators: map, then (read a tag, then the fields that go with it), one_of, succeed and fail.
  • Running: run, from_string and from_bytes.

A decoder only checks shape. Rules about the values themselves (a symbol's length, a positive quantity) belong to the type that owns them.