How to decode a JSON string in Go by example?

How to create multiple goroutines && how the goroutine scheduler behaves with three logical processors.

Example

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name  string `json:"name"`
	Age   int    `json:"age"`
	Email string `json:"email"`
}

func main() {
	jsonStr := `{
        "name":"John Doe",
        "age":30,
        "email":"john.doe@gmail.com"
    }`

	var p Person
	err := json.Unmarshal([]byte(jsonStr), &p)
	if err != nil {
		fmt.Println("Error decoding JSON:", err)
		return
	}

	fmt.Println("Name:", p.Name)
	fmt.Println("Age", p.Age)
	fmt.Println("Email:", p.Email)
	fmt.Println("Decoded JSON:", p)
}

Output

Name: John Doe
Age 30
Email: john.doe@gmail.com
Decoded JSON: {John Doe 30 john.doe@gmail.com}

Explaination

In this example, we define a Person struct with two fields: Name and Age. We also use struct tags to indicate the JSON keys that correspond to each field.

We then define a jsonStr variable containing a JSON-encoded string representing a Person object.

To decode the JSON string, we create a Person variable p and use the json.Unmarshal() function to unmarshal the JSON data into it. The first argument to json.Unmarshal() is a byte slice containing the JSON data, and the second argument is a pointer to the variable we want to populate with the decoded data.

If there is an error decoding the JSON data, json.Unmarshal() returns an error, which we handle by printing an error message and returning from the main() function.

Finally, we print out the decoded Person object to the console using fmt.Println().

I hope this helps! Let me know if you have any further questions.