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.
Use this package for APIs, config files and anything another program will read. Its neighbours: encoding.yaml and encoding.toml for files people edit, encoding.msgpack when the data should be small and binary, and encoding.serde to read or write the same struct in several formats.
The things people get wrong:
•
GetInt returns an int, 32 bits, and clamps anything larger: 3000000000 comes back as 2147483647. For ids and timestamps, read the field with Unmarshal into an i64, or parse the text from Get.
•
Get, GetInt and Has look only at the top level of an object. For nested values use GetPath, such as GetPath(text, "user.address.city").
•
Strict or lenient. Unmarshal throws on a missing field, an unknown key or a type that does not match; UnmarshalLenient keeps the struct's defaults for missing fields and skips unknown keys, but a wrong type still fails.
•
Key order. Marshal writes fields in struct order. A decoded Value object keeps the order of the text and Encode writes its keys in that order; pass sort_keys to Encode when output must be alphabetical.
Guide: load a config file into a struct
A config file is the most common JSON a program reads. Describe it as structs, give every field the default you want, and let UnmarshalLenient fill in what the file has. Nested objects map to nested structs and arrays map to Vector fields.
name: shop
debug: false
database: db.internal 6432 pool 4
admins: 2 sara reza
The file left out debug and db.pool, so they keep their defaults. That is the reason for the lenient form here: plain Unmarshal is strict and fails with missing key 'pool' when a field is absent, and with unknown key when the file has a key the struct does not. Strict is right for messages between programs, where a missing field is a bug; lenient is right for files people edit by hand. To read a file from disk, pass the text of fs.ReadAll from fs.
Guide: build an API response
Going the other way, Marshal turns a struct into compact JSON for the wire and MarshalIndent into readable JSON for logs and files. A Vector of structs becomes an array of objects, quotes inside strings are escaped, and the field order is the order of the struct.
@json "price_cents" renames a field in the JSON without renaming it in the code, and @json "-" keeps internal fields such as cache_key out of the output. Use it for passwords and tokens too, so they can never leak into a response by accident.
Guide: explore JSON of unknown shape
When you do not know the shape ahead of time, for example a webhook from another service, Decode gives a tree of Value nodes. Ask each node what it is with IsString, IsInt, IsObject and the rest, then read it with the matching As function. Where a value must be there and of one kind, the checked methods are shorter: doc.field("size").field("w").int() throws MissingKey or TypeMismatch instead of quietly giving 0.
keys: 7
id = int 7
name = string Lamp
price = float 19.5
sale = bool true
tags = array of 2
size = object with 2 keys
note = null
color is missing
area: 900
expected an integer, got a number
Whole numbers come back as int and numbers with a fraction as float; IsNumber accepts both. A decoded object keeps its keys in the order of the text, but a sender is free to change that order, so walk a list of the keys you expect, as this program does, and use ObjectHas for the optional ones.
Guide: report bad input
Decode, Unmarshal, UnmarshalLenient and a decoder's Decode are declared throw: on bad input they throw an Error and give back nothing half-read. Catch it with try: ... catch e:, or write try before the call in a function that is itself declared throw to pass it on. e.kind says what went wrong (Syntax, UnexpectedEnd, TypeMismatch, MissingKey, OutOfRange and so on), e.message says it in words, and e.line and e.column point at the spot in the text, which is what you show the user; e.to_str() puts it all on one line. Data after a complete value has the code json.trailing_data. The text helpers like Get never fail; they return an empty string for a missing key, so check with Has or Valid first when that matters.
ok: a@example.com 31
type mismatch at line 1 column 35 -> value does not match the expected type
unexpected end of input at line 1 column 37 -> expected ',' or '}'
invalid argument at line 1 column 47 -> unknown key
lenient ok: a@example.com 31
valid: true false
missing key gives []
Guide: stream newline-delimited JSON
Logs and exports often hold one JSON value per line (NDJSON). A decoder reads them one at a time: More says whether another value is left, and Decode returns the next one. NewBufDecoder reads from a string and NewDecoder from an open file. Encoders write the same format, one value per line.
{"name":"Maryam","age":28,"tags":["admin"]}
{
"name": "Maryam",
"age": 28,
"tags": [
"admin"
]
}
Reza 41 2
type mismatch json: value does not match the expected type (line 1, column 25)
Sara
{"$schema":"https://json-schema.org/draft/2020-12/schema","$defs":{"User":{"title":"User","type":"object","properties":{"name":{"type":"string"},"age":{"type":"integer","format":"int32"},"tags":{"type":"array","items":{"type":"string"}}},"required":["name","age","tags"],"additionalProperties":false}},"$ref":"#/$defs/User"}
true
funcUnmarshal<T>(text: str, out &: T): Throws<bool>
Fills the struct out from JSON. Every field has to be present with a matching type and an unknown key is an error too; on failure it throws an Error with the kind, the message and the line and column in the text.
The value of a top-level key as raw JSON text: a string keeps its quotes and escapes, so the result can be passed to Unmarshal. An empty text means the key is missing.
Follows a dotted path through objects and arrays, such as hits.hits.0._source; strings come back decoded, anything else as raw JSON, and a missing step gives an empty string.