JSON in Go
Go: JSON
JSON (JavaScript Object Notation) is a lightweight data format that is easy for humans to read and write and easy for machines to parse and generate. Go provides built-in support for encoding and decoding JSON data using the standard library package
encoding/json
.
Encode a Go data structure to JSON
To encode a Go data structure to JSON, you can use the json.Marshal() function, which takes a Go value and returns a byte slice containing its JSON representation. For example:
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string
Age int
}
func main() {
person := Person{Name: "Alice", Age: 30}
jsonBytes, err := json.Marshal(person)
if err != nil {
panic(err)
}
fmt.Println(string(jsonBytes)) // Output: {"Name":"Alice","Age":30}
}
Decode a Go data structure to JSON
To decode JSON data into a Go data structure, you can use the json.Unmarshal() function, which takes a byte slice containing JSON data and a pointer to a Go value, and sets the value to the decoded data.
For example -
func main() {
jsonStr := `{"Name":"Bob","Age":25}`
var person Person
err := json.Unmarshal([]byte(jsonStr), &person)
if err != nil {
panic(err)
}
fmt.Println(person.Name, person.Age) // Output: Bob 25
}
Note that the field names in the Go struct must be exported (i.e. capitalized) in order to be encoded or decoded by the encoding/json
package. You can use struct tags to specify custom field names in the JSON data.
For example -
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
person := Person{Name: "Charlie", Age: 20}
jsonBytes, err := json.Marshal(person)
if err != nil {
panic(err)
}
fmt.Println(string(jsonBytes)) // Output: {"name":"Charlie","age":20}
}
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go