Используйте json.Marshal
Пример
1 2 3 4 5 6 7 8 9 10 11 12 |
type Employee struct { Name string `json:"empname"` Number int `json:"empid"` } emp := &Employee{Name: "Rocky",Number: 5454} e, err := json.Marshal(emp) if err != nil { fmt.Println(err) return } fmt.Println(string(e)) |
Вот вариант если нужно записать в файл например
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package main import ( "encoding/json" "fmt" "io/ioutil" ) type Rankings struct { Keyword string GetCount uint32 Engine string Locale string Mobile bool } func main() { var jsonBlob = []byte(` {"keyword":"hipaa compliance form", "get_count":157, "engine":"google", "locale":"en-us", "mobile":false} `) rankings := Rankings{} err := json.Unmarshal(jsonBlob, &rankings) if err != nil { // nozzle.printError("opening config file", err.Error()) } rankingsJson, _ := json.Marshal(rankings) err = ioutil.WriteFile("output.json", rankingsJson, 0644) fmt.Printf("%+v", rankings) } |