Go: Reading json files 👀
Let’s do something basic, something simple like reading a json file, in this case we’re going to use ‘ioutils’ with ’encoding’ in json, everything is included in the standard library so no worries about installing third party libraries.
Unfortunately if we want to print like we usually do on python, it is not going to be possible, Go demands the user to decode the json file into a data structure that go understands.
package main
import (
"fmt"
"io/ioutil"
"encoding/json"
)
type Customer struct {
id int
Firstname string
Lastname string
Country string
}
func main() {
jsonReader()
}
func jsonReader() {
jsonData, err := ioutil.ReadFile("fileExample.json")
if err != nil {
fmt.Println(err)
}
fmt.Println("success opening json file, hell yeah")
var dataCust Customer
err = json.Unmarshal(jsonData, &dataCust)
if err != nil {
fmt.Printf("Error during Unmarshal(): ", err)
}
fmt.Printf("name: ", dataCust.Lastname)
}
Notice that this time we specified in advance the structure type that is expected while reading the file, the results as shown below.
#+RESULTS:
success opening json file, hell yeah
name: Sperling
As you can see there is a lot going on there, if you come form python, you have noticed already that script takes longer to be built, that in part is because Go needs to have a better definition of what to expect.
What plans do I have for using go in the future?