Go解析Json檔案
阿新 • • 發佈:2021-06-25
json檔案內容(test.json)
{ "args": {}, "data": "", "files": {}, "form": { "age": "18", "name": "liy" }, "headers": { "Accept-Encoding": "gzip", "Content-Length": "30", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "Go-http-client/1.1", "X-Amzn-Trace-Id": "Root=1-60d5712e-376038381773f32a0ad66c1c" }, "json": null, "origin": "11.22.33.44", "url": "http://httpbin.org/post" }
程式碼如下(go 1.16.5 demo.go)
package main import ( "encoding/json" "fmt" "io/ioutil" ) type KV map[string]string // load json file type result struct { Args KV `json:"args"` Data string `json:"data"` Files KV `json:"files"` Form KV `json:"form"` Headers KV `json:"headers"` Json string `json:"json"` Origin string `json:"origin"` Url string `json:"url"` } func printMap(m KV) { for k, v := range m { fmt.Println(k, v) } } func loadJson() { f, err := ioutil.ReadFile("test.json") if err != nil { fmt.Println(err) return } var config result json.Unmarshal(f, &config) printMap(config.Args) fmt.Println(config.Data) printMap(config.Files) printMap(config.Form) printMap(config.Headers) fmt.Println(config.Json) fmt.Println(config.Origin) fmt.Println(config.Url) } func main() { loadJson() }
編譯,執行
go run demo.go