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.
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go