基础
使用json.Marshal()函数可以对一组数据进行JSON格式的编码
func Marshal(v interface{}) ([]byte, error)
可以使用json.Unmarshal()函数将JSON格式的文本解码为Go里边预期的数据结构。json.Unmarshal()函数的原型如下:
func Unmarshal(data []byte, v interface{}) error
解码未知结构的JSON数据
JSON中的布尔值将会转换为Go中的bool类型;
数值会被转换为Go中的float64类型;
字符串转换后还是string类型;
JSON数组会转换为[]interface{}类型;
JSON对象会转换为map[string]interface{}类型;
null值会转换为nil。
package main
import (
"fmt"
"encoding/json"
)
func main() {
b := []byte(`{
"Title": "Go语言编程",
"Authors": ["XuShiwei", "HughLv", "Pandaman", "GuaguaSong", "HanTuo", "BertYuan","XuDaoli"],
"Publisher": "ituring.com.cn",
"IsPublished": true,
"Price": 9.99,
"Sales": 1000000
}`)
var r interface{}
err := json.Unmarshal(b, &r)
if err != nil{
return
}
gobook, ok := r.(map[string]interface{})//需要先判断目标结构是否为预期的数据类型
if ok {
for k, v := range gobook {
switch v2 := v.(type) {//也是断言,判断v的类型,为了判断interface的实体类型而设置的
case string:
fmt.Println(k, "is string", v2)
case int:
fmt.Println(k, "is int", v2)
case bool:
fmt.Println(k, "is bool", v2)
case []interface{}:
fmt.Println(k, "is an array:")
for i, iv := range v2 {
fmt.Println(i, iv)
}
default:
fmt.Println(k, "is another type not handle yet")
}
}
}
}
json从标准输入流读取json数据并解码
Go内建的encoding/json 包还提供Decoder和Encoder两个类型,用于支持JSON数据的流式读写,并提供NewDecoder()和NewEncoder()两个函数来便于具体实现:
func NewDecoder(r io.Reader) *Decoder
func NewEncoder(w io.Writer) *Encoderfunc readJsonFromOs(){
dec := json.NewDecoder(os.Stdin)//输入的Json数据必须以{}为开始和结尾
enc := json.NewEncoder(os.Stdout)
for {
var v map[string]interface{}
if err := dec.Decode(&v); err != nil {
log.Println(err)
return
}
for k:= range v {
if k != "Title" {
v[k] = nil
}
}
if err := enc.Encode(&v); err != nil {
log.Println(err)
}
}
}