-
Read from Json file and convert to struct
type Record struct { Time time.Time Station string Temperature float64 Rain float64 } func readRecord(fileName string) (Record, error) { file, err := os.Open(fileName) if err != nil { log.Fatal(err) } defer file.Close() var rec Record dec := json.NewDecoder(file) if err := dec.Decode(&rec); err != nil { return Record{}, err } return rec, nil } func main() { fileName := "sample-app/record.json" rec, err := readRecord(fileName) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", rec) }
-
Convert Json string to stuct
type Student struct { Name string // The name must start with upper case Age int } jsonTxt := `[{"name":"tom", "age":13},{"name":"Lily", "age":14}]` var students []Student json.Unmarshal([]byte(jsonTxt), &students) for _, stu := range students { fmt.Printf("%+v", stu) }
-
Convert Map to Json text
func main() {
states := make(map[string]string)
states["WA"] = "Washington"
states["NY"] = "New York"
states["CA"] = "California"
jsonText, _ := json.Marshal(states)
fmt.Println(string(jsonText))
}