JSON
Working with JSON in Go is straightforward and can be achieved using the encoding/json
package, which provides functionalities to encode Go data structures into JSON and decode JSON into Go data structures.
Nice to know Struts Tags
Struct to JSON
Using json.Marshal
is the simple way. The json.NewEncoder
is used to create a new JSON encoder that writes to an io.Writer interface, such as a file or network connection
. This allows you to easily encode Go data structures to JSON and write them to an external destination.
Example
package main
import (
"encoding/json"
"fmt"
"os"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
person := Person{Name: "Gabriel", Age: 25}
jsonData, err := json.Marshal(person)
fmt.Println("Using Marshal")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("JSON Data:", string(jsonData))
fmt.Println("***")
fmt.Println("Using NewEncoder")
file, _ := os.Create("src/http/person.json")
defer file.Close()
err = json.NewEncoder(file).Encode(person)
}
JSON to Struct
Using json.Unmarshal
is the simple way. The json.NewDecoder
is used to create a new JSON decoder that reads from an io.Reader interface, such as a file or network connection
. This enables you to easily decode JSON data from an external source into Go data structures.
Example
package main
import (
"encoding/json"
"fmt"
"os"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
person := Person{Name: "Gabriel", Age: 25}
jsonData, err := json.Marshal(person)
fmt.Println("Using Marshal")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("JSON Data:", string(jsonData))
fmt.Println("***")
fmt.Println("Using NewEncoder")
file, _ := os.Create("src/http/person.json")
defer file.Close()
err = json.NewEncoder(file).Encode(person)
}