Json parser
Works with bucklescript and bsb-native
Basics
open Json.Infix; /* for the nice infix operators */
let raw = {|{"hello": "folks"}|};
let who = Json.parse(raw) |> Json.get("hello") |?> Json.string;
Js.log(who);
Parse & stringify
let stringify = t => string
let text = {|{"hello": "folks", "aa": [2, 3, "four"]}|};
let result = Json.stringify(Json.parse(text));
Js.log(result);
assert(text == result);
Accessing descendents
let get = (string, t) => option(t)
If t
is an object, get the value associated with the given string key
let getPath = (string, t) => option(t)
Get a deeply nested value from an object t
.
open Json.Infix;
let json = Json.parse({|{"a": {"b": {"c": 2}}}|});
let num = Json.getPath("a.b.c", json) |?> Json.number;
assert(num == Some(2.))
Coercing to types
The JSON type
type t = | String(string) | Number(float) | Array(list(t)) | Object(list((string, t))) | True | False | Null
Infix operators for easier working
module Infix
This module does not have a toplevel documentation block.
let |! = (option('a), string) => 'a
The "force unwrap" operator
If you're sure there's a value, you can force it.
open Json.Infix;
let x: int = Some(10) |! "Expected this to be present";
Js.log(x);
But you gotta be sure, otherwise it will throw.
open Json.Infix;
let x: int = None |! "This will throw";
let |? = (option('a), 'a) => 'a
The "upwrap with default" operator
open Json.Infix;
let x: int = Some(10) |? 4;
let y: int = None |? 5;
Js.log2(x, y);
let |?> = (option('a), 'a => option('a)) => option('a)
The "transform contents into new optional" operator
open Json.Infix;
let maybeInc = x => x > 5 ? Some(x + 1) : None;
let x: option(int) = Some(14) |?> maybeInc;
let y: option(int) = None |?> maybeInc;
let |?>> = (option('a), 'a => 'a) => option('a)
The "transform contents into new value & then re-wrap" operator
open Json.Infix;
let inc = x => x + 1;
let x: option(int) = Some(7) |?>> inc;
let y: option(int) = None |?>> inc;
Js.log2(x, y);
let fold = (option('a), 'a, 'a => 'a) => 'a
"handle the value if present, otherwise here's the default"
It's called fold because that's what people call it :?. It's the same as "transform contents to new value" + "unwrap with default".
open Json.Infix;
let inc = x => x + 1;
let x: int = fold(Some(4), 10, inc);
let y: int = fold(None, 2, inc);
Js.log2(x, y);
other items defined