這篇文章主要為大家詳細介紹了go語言處理json數(shù)據(jù)的方法,文中示例代碼介紹的非常詳細,零基礎也能參考此文章,感興趣的小伙伴們可以參考一下。

Go json包
Marshal():Go數(shù)據(jù)對象 -> json數(shù)據(jù)
UnMarshal():Json數(shù)據(jù) -> Go數(shù)據(jù)對象
func Marshal(v interface{}) ([]byte, error)
func Unmarshal(data []byte, v interface{}) error構(gòu)建json數(shù)據(jù)
Marshal()和MarshalIndent()函數(shù)可以將數(shù)據(jù)封裝成json數(shù)據(jù)。
1、struct、slice、array、map都可以轉(zhuǎn)換成json
2、struct轉(zhuǎn)換成json的時候,只有字段首字母大寫的才會被轉(zhuǎn)換
3、map轉(zhuǎn)換的時候,key必須為string
4、封裝的時候,如果是指針,會追蹤指針指向的對象進行封裝
例如:
有一個struct結(jié)構(gòu):
type Post struct {
Id int
Content string
Author string
}這個結(jié)構(gòu)表示博客文章類型,有文章ID,文章內(nèi)容,文章的提交作者。這沒什么可說的,唯一需要指明的是:它是一個struct,struct可以封裝(編碼)成JSON數(shù)據(jù)。
要將這段struct數(shù)據(jù)轉(zhuǎn)換成json,只需使用Marshal()即可。如下:
post := &Post{1, "Hello World", "userA"}
b, err := json.Marshal(post)
if err != nil {
fmt.Println(nil)
}Marshal()返回的是一個[]byte類型,現(xiàn)在變量b就已經(jīng)存儲了一段[]byte類型的json數(shù)據(jù),可以輸出它:
fmt.Println(string(b))
結(jié)果:
{"Id":1,"Content":"Hello World","Author":"userA"}可以在封裝成json的時候進行"美化",使用MarshalIndent()即可自動添加前綴(前綴字符串一般設置為空)和縮進:
c,err := json.MarshalIndent(post,"","\t")
if err != nil {
fmt.Println(nil)
}
fmt.Println(string(c))結(jié)果:
{
"Id": 1,
"Content": "Hello World",
"Author": "userA"
}除了struct,array、slice、map結(jié)構(gòu)都能解析成json,但是map解析成json的時候,key必須只能是string,這是json語法要求的。
例如:
// slice -> json
s := []string{"a", "b", "c"}
d, _ := json.MarshalIndent(s, "", "\t")
fmt.Println(string(d))
// map -> json
m := map[string]string{
"a":"aa",
"b":"bb",
"c":"cc",
}
e,_ := json.MarshalIndent(m,"","\t")
fmt.Println(string(e))返回結(jié)果:
[
"a",
"b",
"c"
]
{
"a": "aa",
"b": "bb",
"c": "cc"
}使用struct tag輔助構(gòu)建json
struct能被轉(zhuǎn)換的字段都是首字母大寫的字段,但如果想要在json中使用小寫字母開頭的key,可以使用struct的tag來輔助反射。
例如,Post結(jié)構(gòu)增加一個首字母小寫的字段createAt。
type Post struct {
Id int `json:"ID"`
Content string `json:"content"`
Author string `json:"author"`
Label []string `json:"label"`
}
postp := &Post{
2,
"Hello World",
"userB",
[]string{"linux", "shell"},
}
p, _ := json.MarshalIndent(postp, "", "\t")
fmt.Println(string(p))結(jié)果:
{
"ID": 2,
"content": "Hello World",
"author": "userB",
"label": [
"linux",
"shell"
]
}使用struct tag的時候,幾個注意點:
1、tag中標識的名稱將稱為json數(shù)據(jù)中key的值
2、tag可以設置為`json:"-"`來表示本字段不轉(zhuǎn)換為json數(shù)據(jù),即使這個字段名首字母大寫
如果想要json key的名稱為字符"-",則可以特殊處理`json:"-,"`,也就是加上一個逗號
3、如果tag中帶有,omitempty選項,那么如果這個字段的值為0值,即false、0、""、nil等,這個字段將不會轉(zhuǎn)換到json中
4、如果字段的類型為bool、string、int類、float類,而tag中又帶有,string選項,那么這個字段的值將轉(zhuǎn)換成json字符串
例如:
type Post struct {
Id int `json:"ID,string"`
Content string `json:"content"`
Author string `json:"author"`
Label []string `json:"label,omitempty"`
}解析json數(shù)據(jù)到struct(結(jié)構(gòu)已知)
json數(shù)據(jù)可以解析到struct或空接口interface{}中(也可以是slice、map等)。理解了上面構(gòu)建json時的tag規(guī)則,理解解析json就很簡單了。
例如,下面是一段json數(shù)據(jù):
{
"id": 1,
"content": "hello world",
"author": {
"id": 2,
"name": "userA"
},
"published": true,
"label": [],
"nextPost": null,
"comments": [{
"id": 3,
"content": "good post1",
"author": "userB"
},
{
"id": 4,
"content": "good post2",
"author": "userC"
}
]
}分析下這段json數(shù)據(jù):
1、頂層的大括號表示是一個匿名對象,映射到Go中是一個struct,假設這個struct名稱為Post
2、頂層大括號里的都是Post結(jié)構(gòu)中的字段,這些字段因為都是json數(shù)據(jù),所以必須都首字母大寫,同時設置tag,tag中的名稱小寫
3、其中author是一個子對象,映射到Go中是另一個struct,在Post中這個字段的名稱為Author,假設名稱和struct名稱相同,也為Author
4、label是一個數(shù)組,映射到Go中可以是slice,也可以是array,且因為json array為空,所以Go中的slice/array類型不定,比如可以是int,可以是string,也可以是interface{},對于這里的示例來說,我們知道標簽肯定是string
5、nextPost是一個子對象,映射到Go中是一個struct,但因為json中這個對象為null,表示這個對象不存在,所以無法判斷映射到Go中struct的類型。但對此處的示例來說,是沒有下一篇文章,所以它的類型應該也是Post類型
6、comment是子對象,且是數(shù)組包圍的,映射到Go中,是一個slice/array,slice/array的類型是一個struct
分析之后,對應地去構(gòu)建struct和struct的tag就很容易了。如下,是根據(jù)上面分析構(gòu)建出來的數(shù)據(jù)結(jié)構(gòu):
type Post struct {
ID int64 `json:"id"`
Content string `json:"content"`
Author Author `json:"author"`
Published bool `json:"published"`
Label []string `json:"label"`
NextPost *Post `json:"nextPost"`
Comments []*Comment `json:"comments"`
}
type Author struct {
ID int64 `json:"id"`
Name string `json:"name"`
}
type Comment struct {
ID int64 `json:"id"`
Content string `json:"content"`
Author string `json:"author"`
}注意,前面在介紹構(gòu)建json數(shù)據(jù)的時候說明過,指針會進行追蹤,所以這里反推出來的struct中使用指針類型是沒問題的。
于是,解析上面的json數(shù)據(jù)到Post類型的對象中,假設這個json數(shù)據(jù)存放在a.json文件中。代碼如下:
func main() {
// 打開json文件
fh, err := os.Open("a.json")
if err != nil {
fmt.Println(err)
return
}
defer fh.Close()
// 讀取json文件,保存到jsonData中
jsonData, err := ioutil.ReadAll(fh)
if err != nil {
fmt.Println(err)
return
}
var post Post
// 解析json數(shù)據(jù)到post中
err = json.Unmarshal(jsonData, &post)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(post)
}輸出結(jié)果:
{1 hello world {2 userA} true [] <nil> [0xc042072300 0xc0420723c0]}也許你已經(jīng)感受到了,從json數(shù)據(jù)反推算struct到底有多復雜,雖然邏輯不難,但如果數(shù)據(jù)復雜一點,這是件非常惡心的事情。所以,使用別人寫好的工具來自動轉(zhuǎn)換吧。本文后面有推薦json到數(shù)據(jù)結(jié)構(gòu)的自動轉(zhuǎn)換工具。
解析json到interface(結(jié)構(gòu)未知)
上面是已知json數(shù)據(jù)結(jié)構(gòu)的解析方式,如果json結(jié)構(gòu)是未知的或者結(jié)構(gòu)可能會發(fā)生改變的情況,則解析到struct是不合理的。這時可以解析到空接口interface{}或map[string]interface{}類型上,這兩種類型的結(jié)果是完全一致的。
解析到interface{}上時,Go類型和JSON類型的對應關系如下
JSON類型 Go類型
---------------------------------------------
JSON objects <--> map[string]interface{}
JSON arrays <--> []interface{}
JSON booleans <--> bool
JSON numbers <--> float64
JSON strings <--> string
JSON null <--> nil例如:
func main() {
// 讀取json文件
fh, err := os.Open("a.json")
if err != nil {
fmt.Println(err)
return
}
defer fh.Close()
jsonData, err := ioutil.ReadAll(fh)
if err != nil {
fmt.Println(err)
return
}
// 定義空接口接收解析后的json數(shù)據(jù)
var unknown interface{}
// 或:map[string]interface{} 結(jié)果是完全一樣的
err = json.Unmarshal(jsonData, &unknown)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(unknown)
}輸出結(jié)果:
map[nextPost:<nil> comments:[map[id:3 content:good post1 author:userB] map[id:4 content:good post2 author:userC]] id:1 content:hello world author:map[id:2 name:userA] published:true label:[]]
上面將輸出map結(jié)構(gòu)。這是顯然的,因為類型對應關系中已經(jīng)說明了,json object解析到Go interface的時候,對應的是map結(jié)構(gòu)。如果將上面輸出的結(jié)構(gòu)進行一下格式化,得到的將是類似下面的結(jié)構(gòu):
map[
nextPost:<nil>
comments:[
map[
id:3
content:good post1
author:userB
]
map[
id:4
content:good post2
author:userC
]
]
id:1
content:hello world
author:map[
id:2
name:userA
]
published:true
label:[]
]現(xiàn)在,可以從這個map中去判斷類型、取得對應的值。但是如何判斷類型?可以使用類型斷言:
func main() {
// 讀取json數(shù)據(jù)
fh, err := os.Open("a.json")
if err != nil {
fmt.Println(err)
return
}
defer fh.Close()
jsonData, err := ioutil.ReadAll(fh)
if err != nil {
fmt.Println(err)
return
}
// 解析json數(shù)據(jù)到interface{}
var unknown interface{}
err = json.Unmarshal(jsonData, &unknown)
if err != nil {
fmt.Println(err)
return
}
// 進行斷言,并switch匹配
m := unknown.(map[string]interface{})
for k, v := range m {
switch vv := v.(type) {
case string:
fmt.Println(k, "type: string\nvalue: ", vv)
fmt.Println("------------------")
case float64:
fmt.Println(k, "type: float64\nvalue: ", vv)
fmt.Println("------------------")
case bool:
fmt.Println(k, "type: bool\nvalue: ", vv)
fmt.Println("------------------")
case map[string]interface{}:
fmt.Println(k, "type: map[string]interface{}\nvalue: ", vv)
for i, j := range vv {
fmt.Println(i,": ",j)
}
fmt.Println("------------------")
case []interface{}:
fmt.Println(k, "type: []interface{}\nvalue: ", vv)
for key, value := range vv {
fmt.Println(key, ": ", value)
}
fmt.Println("------------------")
default:
fmt.Println(k, "type: nil\nvalue: ", vv)
fmt.Println("------------------")
}
}
}結(jié)果如下:
comments type: []interface{}
value: [map[id:3 content:good post1 author:userB] map[author:userC id:4 content:good post2]]
0 : map[id:3 content:good post1 author:userB]
1 : map[id:4 content:good post2 author:userC]
------------------
id type: float64
value: 1
------------------
content type: string
value: hello world
------------------
author type: map[string]interface{}
value: map[id:2 name:userA]
name : userA
id : 2
------------------
published type: bool
value: true
------------------
label type: []interface{}
value: []
------------------
nextPost type: nil
value: <nil>
------------------可見,從interface中解析非常復雜,而且可能因為嵌套結(jié)構(gòu)而導致無法正確迭代遍歷。這時候,可以使用第三方包simplejson,見后文。
解析、創(chuàng)建json流
除了可以直接解析、創(chuàng)建json數(shù)據(jù),還可以處理流式數(shù)據(jù)。
1、type Decoder解碼json到Go數(shù)據(jù)結(jié)構(gòu)
2、ype Encoder編碼Go數(shù)據(jù)結(jié)構(gòu)到json
例如:
const jsonStream = `
{"Name": "Ed", "Text": "Knock knock."}
{"Name": "Sam", "Text": "Who's there?"}
{"Name": "Ed", "Text": "Go fmt."}
{"Name": "Sam", "Text": "Go fmt who?"}
{"Name": "Ed", "Text": "Go fmt yourself!"}
`
type Message struct {
Name, Text string
}
dec := json.NewDecoder(strings.NewReader(jsonStream))
for {
var m Message
if err := dec.Decode(&m); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
fmt.Printf("%s: %s\n", m.Name, m.Text)
}輸出:
Ed: Knock knock. Sam: Who's there? Ed: Go fmt. Sam: Go fmt who? Ed: Go fmt yourself!
再例如,從標準輸入讀json數(shù)據(jù),解碼后刪除名為Name的元素,最后重新編碼后輸出到標準輸出。
func main() {
dec := json.NewDecoder(os.Stdin)
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 != "Name" {
delete(v, k)
}
}
if err := enc.Encode(&v); err != nil {
log.Println(err)
}
}
}上文描述的就是go語言處理json數(shù)據(jù)的方法,具體使用情況還需要大家自己動手實驗使用過才能領會。如果想了解更多相關內(nèi)容,歡迎關注創(chuàng)新互聯(lián)成都網(wǎng)站設計公司行業(yè)資訊頻道!
另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
網(wǎng)站標題:go語言處理json數(shù)據(jù)的方法-創(chuàng)新互聯(lián)
轉(zhuǎn)載來源:http://www.chinadenli.net/article18/dehhgp.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供云服務器、網(wǎng)站導航、標簽優(yōu)化、手機網(wǎng)站建設、網(wǎng)站建設、網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)