golang学习笔记——json数据
生成json格式字符
-
使用结构体生成
package main
import (
"encoding/json"
"fmt"
)
//用于json的结构体类型成员首字母必须大写
// type Jon struct {
// Name string
// Subject []string
// Score int
// }
type Jon struct {
Name string `json:"name"` //指定json中显示的名称,使用"-"表示不输出
Subject []string `json:"su"`
Score int `json:"score,string"` //转为字符串类型
}
func main() {
var js Jon
js = Jon{"cui", []string{"Go", "PHP"}, 20}
fmt.Println(js)
re, err := json.Marshal(js)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(re))
}
-
使用map生成json
package main
import (
"encoding/json"
"fmt"
)
func main() {
m := make(map[string]interface{}, 4)
m["name"] = "cjp"
m["subject"] = []string{"GO", "PHP"}
m["score"] = 32
json, err := json.Marshal(m)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(json))
}
解析json字符串
-
解析到结构体
package main
import (
"encoding/json"
"fmt"
)
type Jon struct {
Name string `json:"name"`
Subject []string `json:"subject"`
Score int `json:"score,string"`
}
type Jon2 struct {
Name string `json:"name"`
}
func main() {
jsonBuf := `{"name":"cjp","score":"32","subject":["GO","PHP"]}`
var tmp1 Jon
json.Unmarshal([]byte(jsonBuf), &tmp1)
fmt.Printf("%+v \n", tmp1)
//只保存指定字段
var tmp2 Jon2
json.Unmarshal([]byte(jsonBuf), &tmp2)
fmt.Printf("%+v", tmp2)
}
-
解析到map
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonBuf := `{"name":"cjp","score":32,"subject":["GO","PHP"]}`
m := make(map[string]interface{})
json.Unmarshal([]byte(jsonBuf), &m)
for key, value := range m {
switch data := value.(type) {
case string:
fmt.Printf("map[%s] = %s \n", key, data)
case []interface{}:
fmt.Printf("map[%s] = %v \n", key, data)
case float64: //这里的32居然是浮点类型,确实没想到
fmt.Printf("map[%s] = %d \n", key, int(data))
}
}
}
-
补充:不能确定变量类型时也可以使用反射获取到变量的类型是什么
package main
import (
"encoding/json"
"fmt"
"reflect"
)
func main() {
jsonBuf := `{"name":"cjp","score":32,"subject":["GO","PHP"]}`
m := make(map[string]interface{})
json.Unmarshal([]byte(jsonBuf), &m)
for _, value := range m {
fmt.Println(reflect.TypeOf(value))
}
}
//**********输出*************
[]interface {}
string
float64