A Complete Guide to JSON in Golang (With Examples)
A Comprehensive Guide to Using JSON in Go | Better Stack Community
A Complete Guide to JSON in Golang
Intro
- Marshalling: The act of converting a Go data structure into valid JSON
- Unmarshalling: The act of parsing a valid JSON string into a data structure in go.
Attention
In other Languages, marshalling is often referred to as “serializing”, while unmarshalling is referred to as “deserializing”.
--- title: Marshalling and Unmarshalling in GO --- flowchart LR A[JSON] B[Go Data Structure] A -- Unmarshalling --> B B -- Marshallling --> A
func main() {
input := `{
"name": "John Doe",
"age": 15,
"hobbies": ["climbing", "cycling", "running"]
}`
var target map[string]any
err := json.Unmarshal([]byte(input), &target)
if err != nil {
log.Fatalf("Unable to marshal JSON due to %s", err)
}
for k, v := range target {
fmt.Printf("k: %s, v: %v\n", k, v)
}
}The map[string]any data type in Go is a Go - Generic Container that can hold values of any type, including complex nested structures.