The encoding/json package in Go provides a straightforward way to encode (convert Go types to JSON) and decode (convert JSON into Go types) data. In this article, we will explore how you can use this package to parse JSON data
Encoding Go Types to JSON
To encode Go data types to JSON, you use the json.Marshal function. Here's a basic example of encoding a Go struct into JSON:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email"`
}
func main() {
person := Person{Name: "Alice", Age: 30, Email: "[email protected]"}
jsonData, err := json.Marshal(person)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(jsonData))
}
In the above example, the json.Marshal function converts a Person object into a JSON byte slice. We then convert and print it as a string.
Decoding JSON to Go Types
To decode JSON into Go types, use the json.Unmarshal function. Below is an example of decoding JSON data into a Go struct:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email"`
}
func main() {
jsonData := []byte(`{"name": "Bob", "age": 25, "email": "[email protected]"}`)
var person Person
err := json.Unmarshal(jsonData, &person)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(person)
}
In this code, json.Unmarshal takes a JSON byte slice and decodes it into a specified Go data structure. You need to supply a pointer to that data structure.
Working with JSON Arrays
The encoding/json package can also handle JSON arrays. Here's how you can decode JSON arrays of objects:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email"`
}
func main() {
jsonData := []byte(`[
{"name": "Alice", "age": 30, "email": "[email protected]"},
{"name": "Bob", "age": 25, "email": "[email protected]"}
]`)
var people []Person
err := json.Unmarshal(jsonData, &people)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(people)
}
Here, a JSON array of Person objects is decoded into a Go slice of Person structs.
Custom JSON Parsing
Sometimes, JSON field names might not align well with Go naming conventions, or you may need custom parsing logic. The json" tags in struct fields help with this.
type CustomPerson struct {
FullName string `json:"name"`
Years int `json:"age"`
}
In the example above, CustomPerson is mapped so that the JSON "name" field is stored in the FullName field and "age" in Years.
By understanding and leveraging these tools specified in the encoding/json package, you can efficiently manage JSON data in your Go applications.