DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Edited on

How to read a file and convert JSON to Go Struct

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())
    }

...



Enter fullscreen mode Exit fullscreen mode

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)
}


Enter fullscreen mode Exit fullscreen mode

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"`
}


Enter fullscreen mode Exit fullscreen mode

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)
}


Enter fullscreen mode Exit fullscreen mode

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! 🍺🍺


You want to support me?

Buy Me A Coffee

Top comments (3)

Collapse
 
tomshaw profile image
Tom Shaw • Edited

New to Go. Tried to piece it all together.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
)

func main() {
    readDirectory()
    readNode()
    readAllNodes()
}

func readDirectory() {
    files, err := ioutil.ReadDir("./data")
    if err != nil {
        log.Fatal(err)
    }

    for _, file := range files {
        fmt.Printf("IsFile: %s\nIsFolder %t\n", file.Name(), file.IsDir())
    }
}

func readNode() {
    content, err := ioutil.ReadFile("./data/player.json")
    if err != nil {
        fmt.Println("Error reading file")
    }

    var creature Creature
    json.Unmarshal([]byte(content), &creature)

    fmt.Println()
    fmt.Println("Creature name: " + creature.Name)
    fmt.Printf("Creature Tags: %q\n", creature.Tags)
    fmt.Printf("Creature value: %+v Notes: %v\n", creature.HP.Value, creature.HP.Notes)
}

func readAllNodes() {
    content, err := ioutil.ReadFile("./data/players.json")
    if err != nil {
        fmt.Println("Error reading file")
    }

    var creature []Creature
    json.Unmarshal([]byte(content), &creature)

    for i := 0; i < len(creature); i++ {
        creatureName := creature[i].Name
        creatureTags := creature[i].Tags
        creatureHP := creature[i].HP

        fmt.Println()
        fmt.Println("Creature name: " + creatureName)
        fmt.Printf("Creature Tags: %q\n", creatureTags)
        fmt.Printf("Creature value: %+v Notes: %v\n", creatureHP.Value, creatureHP.Notes)
    }
}

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"`
}

Enter fullscreen mode Exit fullscreen mode
  {
    "name": "Mutant",
    "tags": [
      "wisdom",
      "ability"
    ],
    "HP": {
      "value": "1",
      "notes": "Player notes."
    }
  }
Enter fullscreen mode Exit fullscreen mode
[
  {
    "name": "Mutant",
    "tags": [
      "wisdom",
      "ability"
    ],
    "HP": {
      "value": "1",
      "notes": "Player notes."
    }
  }
]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mxglt profile image
Maxime Guilbert

Did everything worked as desired?

Collapse
 
tomshaw profile image
Tom Shaw

Absolutely. Go is a fun easy language to learn. Thanks :)