JSON
is a JSON data type, parser, and serializer for Carp.
Installation
(load "git@github.com:carpentry-org/json@0.1.0")
Usage
; Parse JSON
(match (JSON.parse "{\"name\": \"carp\"}")
(Result.Success j) (println* &j)
(Result.Error e) (IO.errorln &e))
; Build JSON
(def j (JSON.obj [(JSON.entry @"name" (JSON.Str @"carp"))
(JSON.entry @"version" (JSON.Num 1.0))]))
; Access values
(JSON.get &j "name") ; => (Maybe.Just (JSON.Str "carp"))
as-arr
(Fn [(Ref JSON a)] (Maybe (Array (Box JSON))))
(as-arr j)
extracts a copy of the array value, or Nothing.
as-bool
(Fn [(Ref JSON a)] (Maybe Bool))
(as-bool j)
extracts the boolean value, or Nothing if not a bool.
as-num
(Fn [(Ref JSON a)] (Maybe Double))
(as-num j)
extracts the numeric value, or Nothing if not a number.
as-obj
(Fn [(Ref JSON a)] (Maybe (Map String (Box JSON))))
(as-obj j)
extracts a copy of the object map, or Nothing.
as-str
(Fn [(Ref JSON a)] (Maybe String))
(as-str j)
extracts a copy of the string value, or Nothing.
entry
(Fn [a, b] (Pair a (Box b)))
(entry k v)
creates a key-value pair for use with obj. The value is
automatically boxed.
get
(Fn [(Ref JSON a), (Ref String a)] (Maybe JSON))
(get j k)
looks up a key in a JSON object. Returns Nothing if the value is
not an object or the key is absent. Returns a copy of the value.
get-in
(Fn [(Ref JSON a), (Ref (Array String) b)] (Maybe JSON))
(get-in j keys)
performs nested key lookup through objects. Returns a copy.
(JSON.get-in &j &[@"data" @"users"])
nth
(Fn [(Ref JSON a), Int] (Maybe JSON))
(nth j i)
indexes into a JSON array. Returns Nothing if the value is not an
array or the index is out of bounds. Returns a copy of the value.
obj
(Fn [(Array (Pair String (Box JSON)))] JSON)
(obj entries)
builds a JSON object from an array of key-value pairs.
(JSON.obj [(JSON.entry @"a" (JSON.Num 1.0))
(JSON.entry @"b" (JSON.Bool true))])
parse
(Fn [(Ref String a)] (Result JSON String))
(parse s)
parses a JSON value from a string.
Returns a (Result JSON String) -- a Success with the parsed value, or an
Error with a message describing what went wrong.
str
(Fn [(Ref JSON a)] String)
(str j)
serializes a JSON value to its string representation.
Produces compact output with no extra whitespace.