Today, we will see how to read files and how to convert JSON files to Go struct!
1 - How to read the list of files in a folder
First, How to read the list of files in a folder?
With the library io/ioutil
it's really simple. With the following code, you will be able to list all the files in a folder and see if it's a directory or not.
package main
import (
"io/ioutil"
"log"
)
...
files, err := ioutil.ReadDir("./path/to/a/folder")
if err != nil {
log.Fatal(err)
}
for _, file := range files {
fmt.Println(file.Name(), file.IsDir())
}
...
2 - How to read a file ?
Still with the library io/ioutil
, it's really simple and only in a few lines of codes.
content, err := ioutil.ReadFile("file_name.txt")
if err != nil {
log.Fatal(err)
}
3 - How to convert JSON file to Go struct ?
As we know how to read a file, we will see how to convert it in Go struct. With the content of the file we are able to transform it to an instance of a struct.
But first, to let the application how to do the mapping, we need to do some stuff in the struct declaration that we want to use.
For each field, we need to add a json
parameter to let know what is the equivalent json name.
type Creature struct {
Name string `json:"Name"`
Tags []string `json:"Tags"`
HP CreatureHP `json:"HP"`
}
type CreatureHP struct {
Value int `json:"Value"`
Notes string `json:"Notes"`
}
Now that we have our Creature
struct ready, we can do the transformation with the following code:
// Declaration of the instance of the struct that we want to fill
creature := bestiary.Creature{}
// Fill the instance from the JSON file content
err = json.Unmarshal(content, &creature)
// Check if is there any error while filling the instance
if err != nil {
panic(err)
}
And that's it! Now, you can use this instance as all the other one that you can create in your Golang application!
I hope it will help you! 🍺🍺
Top comments (3)
New to Go. Tried to piece it all together.
Did everything worked as desired?
Absolutely. Go is a fun easy language to learn. Thanks :)