In this tutorial, we will walk through creating a Go application that generates random user profiles and stores them in a JSON file. By the end of this tutorial, you will have a solid understanding of the following concepts in Go :
In Go, we often need to organize data. This is where structs come into play.
A struct is a collection of fields that group related data together. Here, we will define aProfile struct
to represent user profiles.
type Profile struct {
Name string `json:"name"`
Age int `json:"age"`
Job string `json:"job"`
Hobby string `json:"hobby"`
}
Name
, Age
, Job
, and Hobby
are fields that make up a profile.In Go, slices are dynamically sized arrays. We will use slices to store multiple profiles.
Example of initializing a slice :
profiles := make([]Profile, numProfiles)
This creates a slice profiles
that can hold numProfiles
profiles.
To generate random data,
Go provides the math/rand
package. In our application,
we will randomly select a Name
, Job
, Hobby
, and Age
for each user profile.
We’ll define predefined lists for names, jobs, and hobbies, and then randomly pick from these lists.
//Predefined lists of names, jobs, and hobbies to randomly choose from
var names = []string{"Alice", "Bob", "Charlie", "David", "Eve"}
var jobs = []string{"Engineer", "Doctor", "Artist", "Teacher", "Pilot"}
var hobbies = []string{"Reading", "Gaming", "Cooking", "Hiking", "Music"}
func generateProfile() Profile {
return Profile{
Name: names[rand.Intn(len(names))], // Random name
Age: rand.Intn(50) + 18, // Random age between 18 and 68
Job: jobs[rand.Intn(len(jobs))], // Random job
Hobby: hobbies[rand.Intn(len(hobbies))], // Random hobby
}
}
rand.Intn(len(names))
generates a random index to select an item from the list.rand.Intn(50) + 18
generates a random age between 18 and 68.Each time the generateProfile
function is called, it returns a new random profile.
Now that we have a list of profiles,
we want to save them in a JSON format.
Go provides the encoding/json
package to easily encode Go structs into JSON.
We’ll create a function to save the profiles to a JSON file.
func saveToFile(profiles []Profile, filename string) {
// Create a new file or overwrite an existing file
file, err := os.Create(filename)
if err != nil {
fmt.Println("Error creating the file:", err)
return
}
defer file.Close() // Ensure the file gets closed after we are done
// Create a JSON encoder and set indentation for readability
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ")
// Encode the profiles slice and write it to the file
if err := encoder.Encode(profiles); err != nil {
fmt.Println("Error encoding JSON:", err)
}
}
json.NewEncoder(file)
creates a new encoder that writes to the specified file.encoder.SetIndent("", " ")
sets the indentation to make the JSON output more readable (each level will be indented with two spaces).encoder.Encode(profiles)
encodes the profiles slice into JSON format and writes it to the file.To save the generated profiles to a file, we will call the saveToFile
function in the main
function.
First, we will prompt the user for how many profiles to generate.
Then, we will generate the requested number of profiles,
store them in the profiles
slice, and finally save the data into a JSON file.
func main() {
var numProfiles int
// Ask the user for the number of profiles to generate
fmt.Print("How many profiles would you like to generate? ")
fmt.Scan(&numProfiles) // Read the input from the user
// Create a slice to hold the generated profiles
profiles := make([]Profile, numProfiles)
// Generate the requested number of profiles
for i := 0; i < numProfiles; i++ {
profiles[i] = generateProfile()
}
// Save the generated profiles to a JSON file
saveToFile(profiles, "profiles.json")
fmt.Println("JSON file generated: profiles.json")
}
fmt.Scan(&numProfiles)
reads the user's input (the number of profiles).generateProfile
.profiles.json
.Here is the complete code that you can use to generate random profiles and save them to a JSON file :
package main
import (
"fmt"
"encoding/json" // Package for encoding and decoding JSON
"os" // Package to handle file operations
"math/rand" // Package for generating random numbers (for Go 1.24+ use "math/rand/v2")
)
// Profile structure defines the fields we want in each profile
type Profile struct {
Name string `json:"name"` // Name field
Age int `json:"age"` // Age field
Job string `json:"job"` // Job field
Hobby string `json:"hobby"` // Hobby field
}
// Predefined lists of names, jobs, and hobbies to randomly choose from
var names = []string{"Alice", "Bob", "Charlie", "David", "Eve"}
var jobs = []string{"Engineer", "Doctor", "Artist", "Teacher", "Pilot"}
var hobbies = []string{"Reading", "Gaming", "Cooking", "Hiking", "Music"}
// Function to generate a random profile
func generateProfile() Profile {
// Create a new Profile with random values
return Profile{
Name: names[rand.Intn(len(names))], // Randomly choose a name
Age: rand.Intn(50) + 18, // Randomly generate an age between 18 and 68
Job: jobs[rand.Intn(len(jobs))], // Randomly choose a job
Hobby: hobbies[rand.Intn(len(hobbies))], // Randomly choose a hobby
}
}
// Function to save the generated profiles to a JSON file
func saveToFile(profiles []Profile, filename string) {
// Try to create a new file with the specified filename
file, err := os.Create(filename)
if err != nil {
// If there is an error creating the file, print it and return
fmt.Println("Error creating the file:", err)
return
}
// Ensure the file is closed once the function finishes
defer file.Close()
// Create a new JSON encoder to write to the file
encoder := json.NewEncoder(file)
// Set indentation for better readability of the output JSON
encoder.SetIndent("", " ")
// Encode the profiles slice into JSON and write it to the file
if err := encoder.Encode(profiles); err != nil {
// If there is an error encoding the data into JSON, print it
fmt.Println("Error encoding JSON:", err)
}
}
func main() {
var numProfiles int
// Ask the user how many profiles they want to generate
fmt.Print("How many profiles would you like to generate? ")
// Read the number of profiles from the user's input
fmt.Scan(&numProfiles)
// Create a slice to hold the generated profiles
profiles := make([]Profile, numProfiles)
// Generate the requested number of profiles
for i := 0; i < numProfiles; i++ {
// Store each generated profile in the profiles slice
profiles[i] = generateProfile()
}
// Save the generated profiles to a JSON file
saveToFile(profiles, "profiles.json")
// Inform the user that the file has been created
fmt.Println("JSON file generated: profiles.json")
}
Run the code with :
go run main.go
If everything works correctly, you will see something like this :
How many profiles would you like to generate? 3
JSON file generated: profiles.json
You will find a generated file named profiles.json
in your project folder.
Congratulations! You've just learned how to :
Go is a powerful language for systems programming, web development, and much more. Now that you've learned how to work with structs, slices, and JSON, you're ready to tackle more advanced Go topics like concurrency, web servers, and APIs.
🚀 Thank you for reading these articles! If you find this content valuable and want to support my work, a coffee would be greatly appreciated! ☕😊
💻 I am a freelance web developer, and I personally create and maintain this website. Any support would help me improve and expand it further! 🙌