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
}
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:
Opening the File: First, we try to open the JSON file. If something goes wrong, we show an error message.
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.
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.
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)
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 errorsreturn nil, errors.New("error message")
, but here again it could be OK for an example@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.
Great then, you have a good approach.
Code review apart, I recommend you the following lib
tidwall / gjson
Get JSON values quickly - JSON parser for Go
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
: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.
Jeffail / gabs
For parsing, creating and editing unknown or dynamic JSON in Go
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 theencoding/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:
Without modules:
Parsing and searching JSON