Hello Everyone,
I spent sometime today to craft this code, so this article slowly walk you through how to build a nested struct, how to load data into it, then converting it into JSON, writing to a file, reading from a file and append new data etc.
I was learning GoLang and found needed something like this. Hope it helps.
package main
import (
"encoding/json"
"fmt"
"os"
)
type Schema struct {
Users map[string]User
Posts map[string]Post
}
type User struct {
Username string `json:"username"`
Email string `json:"email"`
}
type Post struct {
Heading string `json:"post_heading"`
Description string `json:"description"`
}
func main() {
u1 := User{
Username: "rajag",
Email: "rajag@example.com",
}
p1 := Post{
Heading: "Post 1 heading",
Description: "Post 1 description",
}
fmt.Println(u1)
fmt.Println(p1)
schema := Schema{
Users: make(map[string]User),
Posts: make(map[string]Post),
}
schema.Users[u1.Username] = u1
schema.Posts[p1.Heading] = p1
fmt.Println(schema)
data, err := json.Marshal(schema)
if err != nil {
fmt.Println(err)
}
u2 := User{
Username: "user2",
Email: "user2@example.com",
}
p2 := Post{
Heading: "Post 2 heading",
Description: "Post 2 description",
}
schema.Users[u2.Username] = u2
schema.Posts[p2.Heading] = p2
data, err = json.Marshal(schema)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%s\n", data)
schema2 := Schema{
Users: make(map[string]User),
Posts: make(map[string]Post),
}
err = json.Unmarshal(data, &schema2)
if err != nil {
fmt.Println(err)
}
fmt.Println("Read from schema 2 >>>>>> ", schema2)
u3 := User{
Username: "user3",
Email: "user3@example.com",
}
p3 := Post{
Heading: "Post 3 heading",
Description: "Post 3 description",
}
schema2.Users[u3.Username] = u3
schema2.Posts[p3.Heading] = p3
data, err = json.Marshal(schema2)
if err != nil {
fmt.Println(err)
}
fmt.Printf("data from schema 2 >>>>>>> %s\n ", data)
fileName := "./my.json"
err = os.WriteFile(fileName, data, 0755)
if err != nil {
fmt.Println(err)
}
schema3 := Schema{
Users: make(map[string]User),
Posts: make(map[string]Post),
}
dataFromFile, err := os.ReadFile(fileName)
if err != nil {
fmt.Println(err)
}
err = json.Unmarshal(dataFromFile, &schema3)
if err != nil {
fmt.Println(err)
}
fmt.Println("schema3 >>>>> ", schema3)
u4 := User{
Username: "user4",
Email: "user4@example.com",
}
p4 := Post{
Heading: "Post 4 heading",
Description: "Post 4 description",
}
schema3.Users[u4.Username] = u4
schema3.Posts[p4.Heading] = p4
data, err = json.Marshal(schema3)
if err != nil {
fmt.Println(err)
}
fmt.Printf("Schema4 >>>>> data %s\n", data)
os.WriteFile(fileName, data, 0755)
}