encoding/json模塊可將json格式字符串,轉換為go struct類型
第一種情況:已知json格式
主要功能函數如下:
func Unmarshal(data []byte, v interface{}) error
函數第一個參數為字節數組,第二個參數為轉換結果可以是任意類型,實現將json格式數據解析成對應結構體
數組對應slice, json的key對應結構體字段,能夠被賦值的字段,首字母必須大寫
使用如下:
package main
import (
"encoding/json"
"fmt"
)
type Server struct {
ServerName string
ServerIP string
}
type Serverslice struct {
Servers []Server
}
func main() {
var s Serverslice
str := `{"servers":[{"serverName": "Shanghai_VPN", "serverIP": "127.0.0.1"}, {"serverName":
"Beijing_VPN", "serverIP": "127.0.0.2"}]}`
_ = json.Unmarshal([]byte(str), &s)
fmt.Println(s)
}
----------------------------------------------------------
輸出為Serverslice類型:
結果:{[{Shanghai_VPN 127.0.0.1} {Beijing_VPN 127.0.0.2}]}
第二種情況:被解析的json數據格式不清楚
使用interface{}存儲
package main
import (
"encoding/json"
"fmt"
)
func main() {
b := []byte(`{"Name": "Wednesday", "age": 6, "Parents": ["Gomez", "Morticia"]}`)
var f interface{}
err := json.Unmarshal(b, &f)
if err != nil{
fmt.Println(err)
}
fmt.Println(f)
}
--------------------------------------------------------------------
結果為Map類型:map[Name:Wednesday age:6 Parents:[Gomez Morticia]]
然后可以通過switch斷言來訪問這些數據。
m := f.(map[string]interface{})
for k, v := range m{
switch vv := v.(type) {
case string:
fmt.Println(k, "is string", vv)
case int:
fmt.Println(k, "is int", vv)
case []interface{}:
fmt.Println(k, "is a array:")
for i, u := range vv{
fmt.Println(i, u)
}
default:
fmt.Println(k, "is of a type I don't know how to hanle")
輸出結果:
Name is string Wednesday
age is int 6
Parents is a array:
0 Gomez
1 Morticia
也可以使用第三方模塊參考https://github.com/bitly/go-simplejson