DEV Community

Cover image for Read JSON file in GoLang (Unstructured Data)
Muhammad Saim
Muhammad Saim

Posted on

Read JSON file in GoLang (Unstructured Data)

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!

Top comments (4)

Collapse
 
ccoveille profile image
Christophe Colombier • Edited

Here is a code review for your function

io.Open+io.RealAll => os.ReadFile , so no need defer

var results map[string]interface{} could be a var results map[string]any

No need to convert byteValue to a []byte when calling unmarshal, it's all ready a []byte

Your function uses hard coded file path in it, it should be a parameter. But it could be OK as a code example.

You are not checking the possible error returned by json.UnMarshal

Don't fmt.Println the errors: change the function signature to return (map[string]any, error) so your code would do this on errors return nil, errors.New("error message"), but here again it could be OK for an example

Collapse
 
muhammadsaim profile image
Muhammad Saim

@ccoveille Thanks for your meaningful input appreciate it. BTW it was my first attempt to learn GoLang so I thought it would be a great idea if I learn something new I'll post it.

Thanks again.

Collapse
 
ccoveille profile image
Christophe Colombier

Great then, you have a good approach.

Collapse
 
ccoveille profile image
Christophe Colombier

Code review apart, I recommend you the following lib

GitHub logo tidwall / gjson

Get JSON values quickly - JSON parser for Go

GJSON
GoDoc GJSON Playground GJSON Syntax

get json values quickly

GJSON is a Go package that provides a fast and simple way to get values from a json document It has features such as one line retrieval, dot notation paths, iteration, and parsing json lines.

Also check out SJSON for modifying json, and the JJ command line tool.

This README is a quick overview of how to use GJSON, for more information check out GJSON Syntax.

GJSON is also available for Python and Rust

Getting Started

Installing

To start using GJSON, install Go and run go get:

$ go get -u github.com/tidwall/gjson
Enter fullscreen mode Exit fullscreen mode

This will retrieve the library.

Get a value

Get searches json for the specified path. A path is in dot syntax, such as "name.last" or "age". When the value is found it's returned immediately.

package main
import "github.com/tidwall/gjson"

const json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}`

func main() {
    value :=
Enter fullscreen mode Exit fullscreen mode

GitHub logo Jeffail / gabs

For parsing, creating and editing unknown or dynamic JSON in Go

Gabs

pkg.go for Jeffail/gabs

Gabs is a small utility for dealing with dynamic or unknown JSON structures in Go. It's pretty much just a helpful wrapper for navigating hierarchies of map[string]interface{} objects provided by the encoding/json package. It does nothing spectacular apart from being fabulous.

If you're migrating from version 1 check out migration.md for guidance.

Use

Import

Using modules:

import (
    "github.com/Jeffail/gabs/v2"
)
Enter fullscreen mode Exit fullscreen mode

Without modules:

import (
    "github.com/Jeffail/gabs"
)
Enter fullscreen mode Exit fullscreen mode

Parsing and searching JSON

jsonParsed, err := gabs.ParseJSON([]byte(`{
 "outer":{
     "inner":{
         "value1":10,
         "value2":22
     },
     "alsoInner":{
         "value1":20,
         "array1":[
             30, 40
         ]
     }
 }
}`))
if err != nil {
    panic(err)
}
var value float64
var ok bool

value, ok = jsonParsed.Path("outer.inner.value1").Data().(float64)
// value == 10.0, ok == true

value, ok = jsonParsed.Search("outer", "inner", "value1").Data().(float64
Enter fullscreen mode Exit fullscreen mode