Logo

Developer learning path

Go

Parsing JSON in Go

Parsing JSON

3

#description

Parsing JSON (JavaScript Object Notation) is the process of converting a JSON string into a usable data structure in Go. JSON is a lightweight format for data exchange, and it is commonly used for data storage and communication between web services.

In order to parse JSON in Go, the encoding/json package is used. This package provides a set of functions and structures that make it easy to decode JSON data into Go data structures, and to encode Go data structures as JSON.

To parse a JSON string into a Go data structure, you need to create a struct that matches the structure of the JSON data. You can then use the json.Unmarshal() function to decode the JSON data into the Go data structure.

For example, suppose you have the following JSON data:

                    
{
    "name": "John",
    "age": 30,
    "isMarried": true,
    "hobbies": ["reading", "sports"]
}
                  

To parse this JSON data into a Go struct, you could define a struct like this:

                    
type Person struct {
    Name      string
    Age       int
    IsMarried bool
    Hobbies   []string
}
                  

And then use the json.Unmarshal() function to decode the JSON data into a Person struct:

                    
var p Person
err := json.Unmarshal(jsonData, &p)
if err != nil {
    // handle error
}
fmt.Println(p.Name)        // outputs "John"
fmt.Println(p.Age)         // outputs 30
fmt.Println(p.IsMarried)   // outputs true
fmt.Println(p.Hobbies[0])  // outputs "reading"
                  

In summary, parsing JSON in Go involves defining a struct that matches the structure of the JSON data, and then using the json.Unmarshal() function to decode the JSON data into the Go data structure.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.