Serialize a value as JSON
#encoding/json marshals exported fields and returns an error when a value cannot be represented.
Fragment
Import encoding/json. The surrounding function returns error.
Reference
Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.
TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.
encoding/json marshals exported fields and returns an error when a value cannot be represented.
Fragment
Import encoding/json. The surrounding function returns error.
Decoding into a struct checks supported value types, but a missing field can remain its zero value. Validate required and domain constraints separately.
Fragment
Import encoding/json, strings and errors. Unmarshal ignores unknown fields; Decoder.DisallowUnknownFields offers a stricter object policy.
TrimSpace trims edge whitespace; Fields splits on runs of whitespace. TrimSuffix removes one matching suffix. len(string) and string slicing count bytes; converting []byte to string makes text from bytes.
Fragment
Import plus independent fragments.
Double quotes interpret escapes; backticks are raw string literals. Single quotes make a rune literal. A string stores bytes; rune is an integer code-point type, not a one-character string.
Fragment
Fragment: imports and type/function declarations at file scope; usage statements inside a function.
len(string) counts bytes. Converting to []rune or ranging a UTF-8 string decodes rune values; indexes from range remain byte offsets. Runes are not grapheme clusters.
Fragment
Fragment: imports and type/function declarations at file scope; usage statements inside a function.
Go strings are immutable byte sequences. Concatenation creates a result; strings.Builder supports incremental construction. Do not copy a nonzero Builder. Conversion to []byte creates mutable bytes.
Fragment
Fragment: imports and type/function declarations at file scope; usage statements inside a function.
encoding/json decodes into a typed destination and reports errors. Unknown fields are ignored by Unmarshal into structs unless a stricter decoder is chosen.
Fragment
Import encoding/json. Missing/zero fields still need application validation.