Standard library
std/json
JSON: parse text into a json.Value tree and encode it back.
let v = try json.parse(`{"name": "gojo", "tags": ["fast", "safe"]}`)
if let name = v.get("name") {
println(name.str() ?? "not a string")
}
var out = json.object()
out.set("ok", json.boolean(true))
println(out.encode()) // {"ok":true}Objects keep their keys in insertion order. Integers that fit in int stay
exact (Int); other numbers are Num (f64).
Constants: maxDepth
Types: enum Value, struct Error
Functions: null, boolean, integer, number, string, array, object, quoted, parse
Constants
maxDepth
pub const maxDepth = 500Deeper nesting is refused: parsing is recursive, and goroutine stacks are small.
Types
enum Value
pub enum Value {
Null
Bool(b: bool)
Int(i: int)
Num(f: f64)
Str(s: String)
Arr(items: Vec[Value])
Obj(fields: Map[String, Value])
}A JSON value. Build one with the functions below (json.object(),
json.string(s)...) or with the variants, and read one with the methods.
Value.isNull
pub fn isNull(self) -> boolWhether this is null.
Value.isObject
pub fn isObject(self) -> boolWhether this is an object.
Value.isArray
pub fn isArray(self) -> boolWhether this is an array.
Value.boolean
pub fn boolean(self) -> ?boolThe value of true or false.
Value.int
pub fn int(self) -> ?intAn integer (also a float with no fractional part that fits).
Value.num
pub fn num(self) -> ?f64A number, integer or not.
Value.str
pub fn str(self) -> ?strThe text of a string.
Value.get
pub fn get(self, key: str) yield ?&ValueThe value at key of an object.
Value.at
pub fn at(self, i: int) yield ?&ValueElement i of an array.
Value.len
pub fn len(self) -> intElements of an array, members of an object, or 0.
Value.keys
pub fn keys(self) -> Vec[String]The keys of an object, in order.
Value.set
pub fn set(inout self, key: str, v: sink Value)Sets a member of an object (does nothing to other values).
Value.push
pub fn push(inout self, v: sink Value)Appends to an array (does nothing to other values).
Value.encode
pub fn encode(self) -> StringCompact JSON text.
Value.pretty
pub fn pretty(self) -> StringJSON text indented by two spaces.
struct Error
pub struct Error {
pub msg: String
// where, from 1
pub line: int
pub column: int
}Why parse failed, and where.
Error.message
pub fn message(self) -> StringThe message, with the line and column.
Functions
null, boolean, integer, number, string, array, object
pub fn null() -> Value
pub fn boolean(b: bool) -> Value
pub fn integer(i: int) -> Value
pub fn number(f: f64) -> Value
pub fn string(s: str) -> Value
pub fn array() -> Value
pub fn object() -> ValueValues to build documents with; array() and object() are empty (add to
them with push and set).
quoted
pub fn quoted(s: str) -> StringQuotes a string as JSON.
parse
pub fn parse(text: str) -> Value ! ErrorParses one JSON value (with nothing but white space after it).