Golang provide structures for the definition of a custom datatype. The concept of structure in Go is similar to the structure in C/C++. Example:
type Person struct {
Name string
Aadhaar int
Street string
HouseNo int
}
Structures in Golang can be written to files like JSON for storing data on a hard drive or for sending over the network. JSON is a lightweight data storage format. Go provides packages in the standard library to write structures to JSON file and retrieving structures from the JSON file. During the definition of structures, additional raw string values know as the field tags may be added to the field declaration which is used as the field name in JSON files. If no additional string value i.e field tag is specified, Go uses the default field name which is used to declare the field in the structure. Structure Definition with Field Tags:
type Person struct {
Name string `json:"name"`
Aadhaar int `json: "aadhaar"`
Street string `json: "street"`
HouseNo int `json: "house_number"`
}
Note : Field name must start with a capital letter if you want to store structure in JSON.
C
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Aadhaar int `json:"aadhaar"`
Street string `json:"street"`
HouseNo int `json:"house_number"`
}
func main() {
var p Person
p.Name = "ABCD"
p.Aadhaar = 1234123412341234
p.Street = "XYZ"
p.HouseNo = 10
fmt.Println(p)
jsonStr, err := json.Marshal(p)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(string(jsonStr))
var str = `{
"name" : "PQRX",
"aadhaar" : 1234123412341234,
"street" : "XYZW",
"house_number" : 10
}`
var p2 Person
err = json.Unmarshal([]byte(str), &p2)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(p2)
}
|
Output:
{ABCD 1234123412341234 XYZ 10}
{"name":"ABCD","aadhaar":1234123412341234,"street":"XYZ","house_number":10}
{PQRX 1234123412341234 XYZW 10}
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
29 Nov, 2022
Like Article
Save Article