Go-26-Json

JSON(JavaScript Object Notation,JavaScript对象表示法)是一种轻量级的数据交换格式,因简单、可读性强被广泛使用。

Go的标准包encoding/json对JSON的支持

JSON编码即将Go数据类型转换为JSON字符串

map转json

package main

import (
"encoding/json"
"fmt"
)

func main() {
m:= map[string][]string{
"name":{"flower"},
"type":{"玫瑰","百合"},
}
// map 转json
if data,err:= json.Marshal(m);err==nil{
fmt.Printf("%s",data)
}
fmt.Println("")
if data,err:= json.MarshalIndent(m,""," ");err==nil{
fmt.Printf("%s",data)
}
}

输出:

{"name":["flower"],"type":["玫瑰","百合"]}
{
"name": [
"flower"
],
"type": [
"玫瑰",
"百合"
]
}
Deb

结构体字段标签

package main

import (
    "encoding/json"
    "fmt"
)

// 通过结构体标签,改变json的key
type User struct {
    name string `json:"_name"`
    age int `json:"_age"`
    sex uint `json:"-"`
    address string
}

func main() {

    user:=User{
        name: "yo",
        age:20,
        sex:1,
        address: "polaris",
    }
    if data,err:= json.MarshalIndent(user,""," ");err==nil{
        fmt.Printf("%s",data)
    }

}

 

posted @ 2020-05-30 15:34  sixinshuier  阅读(157)  评论(0编辑  收藏  举报