encoding/json
Encode JSON, decode dynamic objects and arrays, and preserve exact number text.
Encode JSON#
Marshal(value any) Result<string> encodes null, booleans, strings, all integer widths, finite floats, structs, map[string]any, mixed any[], and dynamic int[], string[], float[], and bool[] arrays. Map keys are sorted; struct fields retain declaration order. Failures use Ocean Result values.
package main;
import "encoding/json";
import "io";
struct Person { Name string; Age int; }
func main() {
text := json.Marshal(Person{"Ada", 36}).unwrap();
value := json.Unmarshal(text).unwrap();
object := value.(map[string]any);
age := object["Age"].(json.Number).Int64().unwrap();
io.Println(text, " age=", age).unwrap();
}
Decode JSON#
Unmarshal(text string) Result<any> returns null, bool, string, json.Number, mixed any[], or map[string]any. Use type assertions to access decoded values. Duplicate object keys keep the last value. Valid(text string) bool validates an entire document. Numbers preserve their original text instead of becoming float64. Number { Text string } supplies Int64() Result<int> and Float64() Result<float> for checked conversion.
Validation and API differences#
The parser validates JSON number grammar, UTF-8, escape sequences, Unicode surrogate pairs, trailing data, and a 128-level nesting limit. Marshal rejects NaN, infinities, unsupported types, and invalid Number text. Strings and JSON input/output use Ocean strings.
Unlike Go, Unmarshal returns a dynamic value rather than filling a destination pointer. Struct encoding includes all declared fields, including private fields, using exact field names. Tags, custom marshalers, struct decoding, fixed arrays, pointers, streaming, indentation, and concrete maps such as map[string]int are not implemented. Use map[string]any for dynamic objects. io.FormatFloat(value float) string supplies locale-independent round-trip float text.
Run the tests#
The tests cover scalar and container encoding, round trips, number precision, invalid documents, nesting, UTF-8, and Unicode escapes.
OCEAN_SRC=/path/to/ocean-src ocean test /path/to/ocean-src/encoding/json