{
"servers": [
{
"serverName": "Shanghai_VPN",
"serverIP": "127.0.0.1"
},
{
"serverName": "Beijing_VPN",
"serverIP": "127.0.0.2"
}
]
}
解析
func Unmarshal(data []byte, v interface{}) error
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)
}
解析到interface{}
在不知道json数据的类型的情况下
- bool 代表 JSON booleans,
- float64 代表 JSON numbers,
- string 代表 JSON strings,
- nil 代表 JSON null.
func main() {
var f interface{}
b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
if err := json.Unmarshal(b, &f); err != nil {
log.Fatalln(err)
}
m := f.(map[string]interface{})
for k, v := range m {
switch vtype := v.(type) {
case int:
fmt.Println(k, "is int: ", vtype)
case string:
fmt.Println(k, "is string: ", vtype)
case float64:
fmt.Println(k, "is float64: ", vtype)
case []interface{}:
fmt.Println(k, "is array: ", vtype)
default:
fmt.Println(k, "is unrecognized: ", vtype)
}
}
}
另外可用simplejson包
生成json
func Marshal(v interface{}) ([]byte, error)
- 字段的 tag 是 "-",那么这个字段不会输出到 JSON
- tag 中带有自定义名称,那么这个自定义名称会出现在 JSON 的字段名中,例如上面例子中 serverName
- tag 中如果带有 "omitempty" 选项,那么如果该字段值为空,就不会输出到 JSON 串中
- 如果字段类型是 bool, string, int, int64 等,而 tag 中带有 ",string" 选项,那么这个字段在输出到 JSON 的时候会把该字段对应的值转换成 JSON 字符串
type Server struct {
// ID 不会导出到 JSON 中
ID int `json:"-"`
// ServerName2 的值会进行二次 JSON 编码
ServerName string `json:"serverName"`
ServerName2 string `json:"serverName2,string"`
// 如果 ServerIP 为空,则不输出到 JSON 串中
ServerIP string `json:"serverIP,omitempty"`
}
s := Server {
ID: 3,
ServerName: `Go "1.0" `,
ServerName2: `Go "1.0" `,
ServerIP: ``,
}
b, _ := json.Marshal(s)
os.Stdout.Write(b)
//stdout
{"serverName":"Go \"1.0\" ","serverName2":"\"Go \\\"1.0\\\" \""}