Load & Parse Json File in Golang
Here is a simple yet practical example of loading and parsing json file in Golang
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
type Page struct {
ID int `json:"id"`
Title string `json:"title"`
Url string `json:"url"`
}
func (p Page) toString() string {
return toJson(p)
}
func toJson(p interface{}) string {
bytes, err := json.Marshal(p)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
return string(bytes)
}
func main() {
pages := getPages()
for _, p := range pages {
fmt.Println(p.toString())
}
fmt.Println(toJson(pages))
}
func getPages() []Page {
raw, err := ioutil.ReadFile("./pages.json")
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
var c []Page
json.Unmarshal(raw, &c)
return c
}
The json file companion as follow:
[
{
"id": 1,
"title": "About Us",
"url": "/about-us"
},
{
"id": 2,
"title": "Team",
"url": "/team"
},
{
"id": 3,
"title": "Projects",
"url": "/projects"
},
{
"id": 4,
"title": "Hire Us",
"url": "/hire-us"
}
]
Thanks to the extensive standard library which make it so easy.