Read JSON file in GoLang (Unstructured Data)

Muhammad Saim - Apr 20 - - Dev Community

In Go programming, we often need to read data from JSON files. Today, we'll talk about a simple way to do this without getting too technical.

Here's a function that reads a JSON file:

// This function reads a JSON file and returns its contents.
func ReadJsonFileWithoutTypes() map[string]interface{} {

    // First, we try to open the JSON file.
    jsonFile, err := os.Open("./data/todos.json")
    if err != nil {
        fmt.Println("Oops! There was a problem opening the file: ", err)
        return nil
    }

    fmt.Println("Yay! The file is open and ready to use.")

    // We make sure to close the file when we're done.
    defer jsonFile.Close()

    // Next, we read the file's content into a special box called a 'byte slice'.
    byteValue, err := io.ReadAll(jsonFile)
    if err != nil {
        fmt.Println("Oops! There was a problem reading the file: ", err)
        return nil
    }

    // Now, we create a container to hold the data from the file.
    var results map[string]interface{}

    // We put the data from the file into our container.
    json.Unmarshal([]byte(byteValue), &results)

    return results
}
Enter fullscreen mode Exit fullscreen mode

Let's Understand the Function

This function, called ReadJsonFileWithoutTypes, helps us read a JSON file and see what's inside. Here's what it does:

  1. Opening the File: First, we try to open the JSON file. If something goes wrong, we show an error message.

  2. Reading the File: If we manage to open the file, we read its contents and put them in a 'byte slice'. It's like a box where we keep the data from the file.

  3. Understanding the Data: Then, we take the data from the 'byte slice' and put it into a special container called a 'map'. This container helps us understand the data better.

  4. Finishing Up: Finally, we return the container with all the data from the JSON file.

That's It!

This function is like a helper that makes it easy for us to read JSON files in our Go programs. We can use it whenever we need to see what's inside a JSON file without worrying too much about complicated stuff.

Now, you can use this function to explore JSON files in your own Go projects! Have fun coding!

. . . . . . . . . . . . . . . . . . . . . . . . . .