Introduction

JSON (JavaScript Object Notation) is a popular data format used for data interchange. Go provides built-in support for working with JSON, making it easy to encode Go data structures into JSON and decode JSON into Go data structures. In this guide, we'll explore how to work with JSON data in Go and provide sample code to demonstrate the process.


Encoding JSON

Go allows you to encode Go data structures into JSON using the "encoding/json" package. You can use the "json.Marshal" function to encode data into JSON. Here's an example:

package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string
Age int
}
func main() {
person := Person{Name: "Alice", Age: 30}
jsonData, err := json.Marshal(person)
if err != nil {
fmt.Println("Error encoding JSON:", err)
return
}
fmt.Println(string(jsonData))
}

In this code, we define a "Person" struct, create an instance, and then use "json.Marshal" to encode it as JSON. The resulting JSON data is printed to the console.


Decoding JSON

You can decode JSON into Go data structures using the "json.Unmarshal" function. Here's an example:

package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string
Age int
}
func main() {
jsonData := []byte(`{"Name":"Bob","Age":25}`)
var person Person
err := json.Unmarshal(jsonData, &person)
if err != nil {
fmt.Println("Error decoding JSON:", err)
return
}
fmt.Printf("Name: %s, Age: %d\n", person.Name, person.Age)
}

In this code, we have JSON data in a byte slice, and we use "json.Unmarshal" to decode it into a "Person" struct, which is then printed to the console.


Working with JSON Objects

JSON data in Go is represented as maps and slices. You can work with these maps and slices to navigate and manipulate JSON data. Here's an example of working with a JSON object:

package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonStr := `{
"name": "John",
"age": 35,
"city": "New York"
}`
var data map[string]interface{}
if err := json.Unmarshal([]byte(jsonStr), &data); err != nil {
fmt.Println("Error decoding JSON:", err)
return
}
name := data["name"].(string)
age := data["age"].(int)
city := data["city"].(string)
fmt.Printf("Name: %s, Age: %d, City: %s\n", name, age, city)
}

In this code, we decode a JSON object into a map, access its values, and print them.


Further Resources

To continue learning about working with JSON data in Go, consider these resources: