[Golang] Save Variables of Any Type in JSON file

Save variables of any type (struct, map, array, slice, etc.) in JSON format file via Golang.

import "os"
import "encoding/json"

func SaveJsonFile(v interface{}, path string) {
        fo, err := os.Create(path)
        if err != nil {
        defer fo.Close()
        e := json.NewEncoder(fo)
        if err := e.Encode(v); err != nil {

// assume we want to save *mystruct* in ``/home/myaccount/mystruct.json``
SaveJsonFile(mystruct, "/home/myaccount/mystruct.json")

Tested on: Ubuntu Linux 15.10, Go 1.5.3.


[1]json - The Go Programming Language