NASutils Knowledge BaseUnofficialPolski

Go · lesson 20 of 30 · Files and errorsRead and write JSON

json.MarshalIndent turns a struct into JSON and json.Unmarshal turns JSON into a struct. Tags name the fields.

Programming on the NAS › Go in 30 lessons

20-json.go Download 20-json.go

package main

import (
	"encoding/json"
	"fmt"
	"os"
)

type Config struct {
	Title  string   `json:"title"`
	Limit  int      `json:"limit"`
	Folder []string `json:"folders"`
}

func main() {
	c := Config{Title: "Morning check", Limit: 90, Folder: []string{"photos", "music"}}
	text, err := json.MarshalIndent(c, "", "  ")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Println(string(text))

	var back Config
	if err := json.Unmarshal([]byte(`{"title":"Evening","limit":80}`), &back); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Printf("%+v\n", back)
}

Terminal

$ ./20-json
{
  "title": "Morning check",
  "limit": 90,
  "folders": [
    "photos",
    "music"
  ]
}
{Title:Evening Limit:80 Folder:[]}

Exercise

Save the config to a file and load it again.

TurboShell does not contain Go. These programs are made in Bucket & Code with its Go runtime; the finished file runs on the NAS without Go.