How to read and write json file in Golang 1.20
In this video we are going to generate source code for the GoLang Program, How to read and write json file using chatGPT.
After generating we will verify and run the generated code.
IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.
##############SOURCE CODE#########################
package main
import (
"encoding/json"
"fmt"
"os"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email"`
}
func main() {
// Create a new Person
person := Person{
Name: "John Doe",
Age: 30,
Email: "johndoe@example.com",
}
// Write the Person to a JSON file
file, err := os.Create("person.json")
if err != nil {
panic(err)
}
defer file.Close()
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ")
err = encoder.Encode(person)
if err != nil {
panic(err)
}
// Read the Person from the JSON file
file, err = os.Open("person.json")
if err != nil {
panic(err)
}
defer file.Close()
decoder := json.NewDecoder(file)
var newPerson Person
err = decoder.Decode(&newPerson)
if err != nil {
panic(err)
}
// Print the new Person
fmt.Println("New Person:")
fmt.Println("Name:", newPerson.Name)
fmt.Println("Age:", newPerson.Age)
fmt.Println("Email:", newPerson.Email)
}
##############END OF SOURCE CODE#########################
Below is the explanation for the program:
The program first defines a Person struct with three fields: Name, Age, and Email. The struct fields are tagged with the json package to specify the names of the fields when they are marshaled to JSON.
Next, the program creates a new Person object and writes it to a JSON file using the json.NewEncoder() function. This function creates a new JSON encoder that writes to a specified file. The SetIndent() function is used to set the indentation level to make the JSON file more readable. The Encode() function is used to write the Person object to the file.
The program then reads the Person object from the JSON file using the json.NewDecoder() function. This function creates a new JSON decoder that reads from a specified file. The Decode() function is used to read the Person object from the file and store it in a new Person object.
Finally, the program prints the new Person object to the console using fmt.Println(). This is just an example of what you could do with the parsed JSON data. You could modify this program to do whatever you need with the parsed JSON data.
#go #goprogramming #golang #golangtutorial #golanguage