Basics of JSON with GoLang
Last Updated :
31 May, 2022
JSON is a widely used format for data interchange. Golang provides multiple encoding and decoding APIs to work with JSON including to and from built-in and custom data types using the encoding/json package.
Data Types: The default Golang data types for decoding and encoding JSON are as follows:
- bool for JSON booleans
- float64 for JSON numbers
- string for JSON strings
- nil for JSON null
- array as JSON array
- map or struct as JSON Object
1. Encoding/Marshalling structs: The Marshal() function in package encoding/json is used to encode the data into JSON.
Syntax: func Marshal(v interface{}) ([]byte, error)
Example:
Go
package main
import (
"fmt"
"encoding/json"
)
type Human struct {
Name string
Age int
Address string
}
func main() {
human1 := Human{ "Ankit" , 23 , "New Delhi" }
human_enc, err := json.Marshal(human1)
if err != nil {
fmt.Println(err)
}
fmt.Println( string (human_enc))
human2 := []Human{
{Name: "Rahul" , Age: 23 , Address: "New Delhi" },
{Name: "Priyanshi" , Age: 20 , Address: "Pune" },
{Name: "Shivam" , Age: 24 , Address: "Bangalore" },
}
human2_enc, err := json.Marshal(human2)
if err != nil {
fmt.Println(err)
}
fmt.Println()
fmt.Println( string (human2_enc))
}
|
Output:
{"Name":"Ankit", "Age":23, "Address":"New Delhi"}
[{"Name":"Rahul", "Age":23, "Address":"New Delhi"}, {"Name":"Priyanshi", "Age":20, "Address":"Pune"}, {"Name":"Shivam", "Age":24, "Address":"Bangalore"}]
2. Decoding/Unmarshalling structs: The Unmarshal() function in package encoding/json is used to unpack or decode the data from JSON to struct.
Syntax: func Unmarshal(data []byte, v interface{}) error
Example:
Go
package main
import (
"fmt"
"encoding/json"
)
type Human struct {
Name string
Address string
Age int
}
func main() {
var human1 Human
Data := [] byte (`{
"Name" : "Deeksha" ,
"Address" : "Hyderabad" ,
"Age" : 21
}`)
err := json.Unmarshal(Data, &human1)
if err != nil {
fmt.Println(err)
}
fmt.Println( "Struct is:" , human1)
fmt.Printf( "%s lives in %s.\n" , human1.Name, human1.Address)
var human2 []Human
Data2 := [] byte (`
[
{ "Name" : "Vani" , "Address" : "Delhi" , "Age" : 21 },
{ "Name" : "Rashi" , "Address" : "Noida" , "Age" : 24 },
{ "Name" : "Rohit" , "Address" : "Pune" , "Age" : 25 }
]`)
err2 := json.Unmarshal(Data2, &human2)
if err2 != nil {
fmt.Println(err2)
}
for i := range human2{
fmt.Println(human2[i])
}
}
|
Output:
Struct is: {Deeksha Hyderabad 21}
Deeksha lives in Hyderabad.
{Vani Delhi 21}
{Rashi Noida 24}
{Rohit Pune 25}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...