To decode JSON data in Go using the encoding/json
package, you'll need to follow these steps:
json.Unmarshal()
function to decode the JSON data into the struct variable.Here's an example to illustrate the process:
package main
import (
"encoding/json"
"fmt"
)
// Define a struct that represents the JSON data structure
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Email []string `json:"email"`
}
func main() {
// JSON data to decode
jsonData := `
{
"name": "John Doe",
"age": 30,
"email": ["[email protected]", "[email protected]"]
}
`
// Create a variable with the defined struct type
var person Person
// Use json.Unmarshal() to decode the JSON data into the struct variable
err := json.Unmarshal([]byte(jsonData), &person)
if err != nil {
fmt.Println("Error decoding JSON data:", err)
return
}
// Access the decoded data
fmt.Println("Name:", person.Name)
fmt.Println("Age:", person.Age)
fmt.Println("Emails:")
for _, email := range person.Email {
fmt.Println("-", email)
}
}
In this example, we define a Person
struct representing the JSON data structure. Then, we create a variable person
of that type to hold the decoded data. We use json.Unmarshal()
to decode the jsonData
into the person
variable. Finally, we can access the decoded data like any other Go struct fields and print them.