encoding/json
Building and reading JSON: from a plain string through automatic struct conversion to streaming.
import encoding.json
There are three ways to work with JSON here. For simple jobs, functions such as Member, Object and Get work directly on JSON text. For real programs, Marshal and Unmarshal convert a Salam struct to JSON and back. For data whose shape you do not know in advance, Decode returns a dynamic Value.
Set the key name of a field with @json "name" above it; @json "-" leaves the field out. Without it, the field's own name becomes the key.
Types
JSONOptions
struct JSONOptionsEncode.| Name | Type | Description |
|---|---|---|
indent | str = "" | The indent unit; empty means one line. |
sort_keys | bool = false | Write the keys in alphabetical order. Without it the key order is not fixed. |
ignore_null | bool = false | Leave out the keys whose value is null. |
import encoding.json
import encoding.value
import encoding.encerr
import fs.file
func main:
mut e := encerr.NoError()
v := json.Decode(`{"city": "Tehran", "zones": [1, 2, 22]}`, e)
println encerr.IsError(e), value.AsString(value.ObjectGet(v, "city"))
println json.EncodeDefault(v)
opts := json.JSONOptions { indent = " ", sort_keys = true }
println json.Encode(v, opts)
_ := json.Decode("[1, 2", e)
println encerr.IsError(e), e.position
mut enc := json.NewBufEncoder()
enc.Encode(value.ValueInt(1))
enc.Encode(value.ValueString("two"))
println enc.String()
enc.Close()
mut pretty := json.NewBufEncoderIndent(" ")
pretty.Encode(v)
println pretty.String()
pretty.Close()
out := file.Open("lines.ndjson", "wb")
mut lines := json.NewEncoder(out)
lines.Encode(value.ValueInt(10))
lines.Encode(value.ValueInt(20))
lines.Close()
mut tabbed := json.NewEncoderIndent(file.Open("pretty.json", "wb"), "\t")
tabbed.Encode(v)
tabbed.Close()
mut reader := json.NewDecoder(file.Open("lines.ndjson", "rb"))
mut total := 0 as i64
until reader.More():
total += value.AsInt(reader.Decode())
end
println total
mut two := json.NewBufDecoder("{\"a\": 1}\n{\"a\": 2}\n")
until two.More():
println json.EncodeDefault(two.Decode())
end
endJSONEncoder
struct JSONEncoder| Name | Type | Description |
|---|---|---|
dst | File* | The destination file, when it writes to one. |
useFile | bool = false | Whether it writes to a file or into memory. |
buf | str.StringBuilder | The text buffer, when it writes into memory. |
indent | str = "" | The indent unit; empty means one value per line. |
count | int = 0 | How many values have been written. |
The example for this item is shown with the ones above: encoding-json-Value.salam
Encode
func Encode(v: value.Value): boolThe example for this item is shown with the ones above: encoding-json-Value.salam
String
func String(): strThe example for this item is shown with the ones above: encoding-json-Value.salam
Close
func Close()The example for this item is shown with the ones above: encoding-json-Value.salam
JSONDecoder
struct JSONDecoder| Name | Type | Description |
|---|---|---|
src | File* | The source file. |
useFile | bool = false | Whether it reads from a file. |
buf | str = "" | The text that was read. |
pos | int = 0 | The current position in the text. |
loaded | bool = false | Whether the file has been read. |
eof | bool = false | It has reached the end of the text. |
bad | bool = false | An error happened while reading. |
The example for this item is shown with the ones above: encoding-json-Value.salam
More
func More(): boolThe example for this item is shown with the ones above: encoding-json-Value.salam
Decode
func Decode(): value.ValueThe example for this item is shown with the ones above: encoding-json-Value.salam
Functions
Valid
func Valid(text: str): boolimport encoding.json
func main:
mut tags := Vector {} as Vector<str>
tags.push(json.Str("hello"))
tags.push(json.Str(`a "quoted" line`))
mut members := Vector {} as Vector<str>
members.push(json.Member("name", "Ali"))
members.push(json.MemberInt("age", 30))
members.push(json.MemberBool("admin", false))
members.push(json.MemberFloat("score", 18.5))
members.push(json.MemberRaw("tags", json.Array(tags)))
text := json.Object(members)
println text
println json.Valid(text), json.Valid("{broken")
println json.Get(text, "name"), json.GetInt(text, "age"), json.GetFloat(text, "score")
println json.Has(text, "admin"), json.Has(text, "email"), json.Keys(text)
println json.Escape("one\ttwo")
pretty := json.Indent(text)
println pretty
println json.Minify(pretty) == json.Minify(text)
println json.Indent4(`{"a":1}`)
println json.IndentTabs(`{"a":1}`) == "{\n\t\"a\": 1\n}", json.IndentWith(`[1]`, "--")
nested := `{"user":{"tags":["a","b"],"name":"Ali"}}`
println json.GetPath(nested, "user.name"), json.GetPath(nested, "user.tags.1"), json.Items(json.GetPath(nested, "user.tags")).len()
println json.Unquote(`"\u0633\u0644\u0627\u0645"`)
endGet
func Get(text: str, key: str): strThe example for this item is shown with the ones above: encoding-json-Build.salam
Escape
func Escape(s: str): strThe example for this item is shown with the ones above: encoding-json-Build.salam
Minify
func Minify(text: str): strThe example for this item is shown with the ones above: encoding-json-Build.salam
Member
func Member(key: str, value: str): str"name": "Ali", for building an object.The example for this item is shown with the ones above: encoding-json-Build.salam
GetInt
func GetInt(text: str, key: str): intThe example for this item is shown with the ones above: encoding-json-Build.salam
GetFloat
func GetFloat(text: str, key: str): f64The example for this item is shown with the ones above: encoding-json-Build.salam
Has
func Has(text: str, key: str): boolThe example for this item is shown with the ones above: encoding-json-Build.salam
MemberInt
func MemberInt(key: str, value: i64): strThe example for this item is shown with the ones above: encoding-json-Build.salam
MemberBool
func MemberBool(key: str, value: bool): strThe example for this item is shown with the ones above: encoding-json-Build.salam
MemberFloat
func MemberFloat(key: str, value: f64): strThe example for this item is shown with the ones above: encoding-json-Build.salam
MemberRaw
func MemberRaw(key: str, raw: str): strThe example for this item is shown with the ones above: encoding-json-Build.salam
Str
func Str(value: str): strThe example for this item is shown with the ones above: encoding-json-Build.salam
Object
func Object(members: Vector<str>): str{...}.The example for this item is shown with the ones above: encoding-json-Build.salam
Array
func Array(items: Vector<str>): str[...].The example for this item is shown with the ones above: encoding-json-Build.salam
IndentWith
func IndentWith(text: str, unit: str): strThe example for this item is shown with the ones above: encoding-json-Build.salam
IndentTabs
func IndentTabs(text: str): strThe example for this item is shown with the ones above: encoding-json-Build.salam
Indent
func Indent(text: str): strThe example for this item is shown with the ones above: encoding-json-Build.salam
Indent4
func Indent4(text: str): strThe example for this item is shown with the ones above: encoding-json-Build.salam
Keys
func Keys(text: str): Vector<str>The example for this item is shown with the ones above: encoding-json-Build.salam
Items
func Items(text: str): Vector<str>Get or Items again.The example for this item is shown with the ones above: encoding-json-Build.salam
Unquote
func Unquote(raw: str): strThe example for this item is shown with the ones above: encoding-json-Build.salam
GetPath
func GetPath(text: str, path: str): strhits.hits.0._source; strings come back decoded, anything else as raw JSON, and a missing step gives an empty string.The example for this item is shown with the ones above: encoding-json-Build.salam
SchemaEnvelope
func SchemaEnvelope<T>(v: T): strSchemaMerge.import encoding.json
import encoding.encerr
struct User:
@json "name"
pub name: str = ""
@json "age"
pub age: int = 0
@json "tags"
pub tags: Vector<str> = Vector {}
@json "-"
pub password: str = ""
end
func main:
mut u := User { name = "Maryam", age = 28, password = "secret" }
u.tags.push("admin")
println json.Marshal(u)
println json.MarshalIndent(u, " ")
mut loaded := User {}
mut e := encerr.NoError()
println json.Unmarshal(`{"name": "Reza", "age": 41, "tags": ["a", "b"]}`, loaded, e)
println loaded.name, loaded.age, loaded.tags.len()
println json.Unmarshal(`{"name": "Reza", "age": "forty"}`, loaded, e), e.message
mut lenient := User {}
println json.UnmarshalLenient(`{"name": "Sara", "extra": 1}`, lenient, e), lenient.name
println json.Schema(u)
envelope := json.SchemaEnvelope(u)
println json.SchemaMerge(envelope) == json.Schema(u)
endSchema
func Schema<T>(v: T): strThe example for this item is shown with the ones above: encoding-json-Marshal.salam
SchemaMerge
func SchemaMerge(envelope: str): strThe example for this item is shown with the ones above: encoding-json-Marshal.salam
Decode
func Decode(text: str, err &: encerr.EncodingError): value.ValueValue; on an error err is filled in.The example for this item is shown with the ones above: encoding-json-Value.salam
Encode
func Encode(v: value.Value, opts: JSONOptions): strValue into JSON with the given options.The example for this item is shown with the ones above: encoding-json-Value.salam
EncodeDefault
func EncodeDefault(v: value.Value): strValue into JSON with the default options.The example for this item is shown with the ones above: encoding-json-Value.salam
NewEncoder
func NewEncoder(f: File*): JSONEncoderThe example for this item is shown with the ones above: encoding-json-Value.salam
NewEncoderIndent
func NewEncoderIndent(f: File*, unit: str): JSONEncoderThe example for this item is shown with the ones above: encoding-json-Value.salam
NewBufEncoder
func NewBufEncoder(): JSONEncoderString.The example for this item is shown with the ones above: encoding-json-Value.salam
NewBufEncoderIndent
func NewBufEncoderIndent(unit: str): JSONEncoderThe example for this item is shown with the ones above: encoding-json-Value.salam
NewDecoder
func NewDecoder(f: File*): JSONDecoderThe example for this item is shown with the ones above: encoding-json-Value.salam
NewBufDecoder
func NewBufDecoder(s: str): JSONDecoderThe example for this item is shown with the ones above: encoding-json-Value.salam
Marshal
func Marshal<T>(v: T): strThe example for this item is shown with the ones above: encoding-json-Marshal.salam
MarshalIndent
func MarshalIndent<T>(v: T, unit: str): strMarshal, indented.The example for this item is shown with the ones above: encoding-json-Marshal.salam
Unmarshal
func Unmarshal<T>(text: str, out &: T, err &: encerr.EncodingError): boolout from JSON. The types have to match and an unknown key is an error too; on failure err is filled in and it returns false.The example for this item is shown with the ones above: encoding-json-Marshal.salam
UnmarshalLenient
func UnmarshalLenient<T>(text: str, out &: T, err &: encerr.EncodingError): boolUnmarshal, but it ignores unknown keys.The example for this item is shown with the ones above: encoding-json-Marshal.salam