No matter which programming language you are working with, you would have to encounter dealing with JSON data.
In this article, we would be looking at how can we work with JSON in Golang. Also, we would be understanding what the Golang jargons (Marshal, Unmarshal, Encode, and Decode) mean.
Convert JSON data into Golang Struct
For parsing incoming JSON data into a Golang struct, we can use the Unmarshal method of the json package.
Unmarshal means: JSON Data ---> Golang Struct
package main
import (
"encoding/json"
"fmt"
)
type Student struct {
Name string
Age int
Country string
}
func main() {
incomingJSON := `
{
"name": "Jon Doe",
"age":18,
"country": "USA"
}
`
var student Student
/*
the Unmarshal method will store the parsed JSON data
in the address of the student variable
*/
err := json.Unmarshal([]byte(incomingJSON), &student)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("Student Struct: %+v", student)
return
}
Run the above code here.
In the above code, we only had one item in the incoming JSON data.
What if we had multiple items in the JSON data. Well, not a problem.
Here's how we would tackle that scenario:
package main
import (
"encoding/json"
"fmt"
)
type Student struct {
Name string
Age int
Country string
}
func main() {
incomingJSON := `
[
{
"name": "Jon Doe",
"age":18,
"country": "USA"
},
{
"name": "Jane Doe",
"age":20,
"country": "United Kingdom"
}
]
`
// incomeJSON has multiple items
var students []Student
err := json.Unmarshal([]byte(incomingJSON), &students)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("Students: %+v", students)
return
}
Run the above code here.
Convert Golang Struct values into JSON String
Marshal means: Golang Struct Values ---> JSON String
package main
import (
"encoding/json"
"fmt"
)
type Student struct {
Name string
Age int
Country string
}
func main() {
student := &Student{
Name: "Jon Doe",
Age: 18,
Country: "USA",
}
jsonBytes, err := json.Marshal(student)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(jsonBytes))
return
}
Run the above code here.
We have two more methods for handling JSON data.
- json.NewEncoder
It is used to encode Go values to JSON format. This is useful while making POST requests to an endpoint with a JSON payload.
- json.NewDecoder
It is used to decode JSON data into Go values. This is the same as json.Unmarshal. However, the NewDecoder method is preferred if your JSON data is coming from an io.Reader, whereas the Unmarshal method, is preferred when the JSON data is already present in the memory.
I will discuss these two methods in a different post.
I hope you a reader must have understood the concept that I have tried to explain in this article.
๐ก Any kind of constructive criticism is highly appreciated and welcomed.
Feel free to connect with me on LinkedIn or Twitter
Cheers โ๏ธ