Go---->JSON
GO | JSON |
---|
bool | bool |
浮点数/整数 | 常规数字 |
string(utf-8) | string(Unicode) |
array/slice | array |
[]byte | string(Base64) |
struct | JSON对象 |
map[string]T | JSON对象 |
注意
- 特殊字符,比如’<'会转义成\u003c
- slice类型的0值为转化为null
- 结构体中只有大写字母开头的字段才会被转化输出,这些字段会作为JSON对象的字符串索引
- map类型必须是map[string]T(T可以是encoding/json包支持的任意数据类型)格式
编码解码
使用json.Marshal()函数将数据编码为JSON格式
使用json.Unmarshal()函数将JSON格式数据解码成Go中的数据结构
JSON---->Go(JSON未知结构)
JSON | GO |
---|
bool | bool |
数值 | float64 |
string | string |
Array | []interface{} |
JSON对象 | map[string]interface{} |
null | nil |
解码代码
package main
import (
"encoding/json"
"fmt"
"log"
)
func main() {
b := []byte(`{
"Title":"Go语言编程",
"Authors":["XuShiwei","Tyler","Pandaman","HanTuo"],
"Publisher":"ituring.com.cn",
"IsPublished":true,
"Price":9.99,
"Sales":1000000}`)
var r interface{}
err := json.Unmarshal(b, &r)
if err != nil {
log.Fatal(err)
}
fmt.Println(r)
gobook, ok := r.(map[string]interface{})
if ok {
for k, v := range gobook {
switch v2 := v.(type) {
case string:
fmt.Println(k, "is string", v2)
case int:
fmt.Println(k, "is int", v2)
case float64:
fmt.Println(k, "is float64", v2)
case bool:
fmt.Println(k, "is bool", v2)
case []interface{}:
fmt.Println(k, "is array")
for i, iv := range v2 {
fmt.Println(i, iv)
}
default:
fmt.Println(k, "is another type not handle yet")
}
}
}
}
结果
map[Authors:[XuShiwei Tyler Pandaman HanTuo] IsPublished:true Price:9.99 Publisher:ituring.com.cn Sales:1e+06 Title:Go语言编程]
Sales is float64 1e+06
Title is string Go语言编程
Authors is array
0 XuShiwei
1 Tyler
2 Pandaman
3 HanTuo
Publisher is string ituring.com.cn
IsPublished is bool true
Price is float64 9.99