欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Go處理json數(shù)據(jù)方法詳解(Marshal,UnMarshal)

 更新時間:2022年04月18日 09:20:05   作者:駿馬金龍  
這篇文章主要介紹了Go處理json數(shù)據(jù)的方法詳解,Marshal(),UnMarshal(),需要的朋友可以參考下

json數(shù)據(jù)格式

參見json數(shù)據(jù)格式說明

如果沒操作過json數(shù)據(jù),建議先看下上面的文章,有助于理解本文后面的內(nèi)容。

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

構建json數(shù)據(jù)

Marshal()和MarshalIndent()函數(shù)可以將數(shù)據(jù)封裝成json數(shù)據(jù)。

  • struct、slice、array、map都可以轉(zhuǎn)換成json
  • struct轉(zhuǎn)換成json的時候,只有字段首字母大寫的才會被轉(zhuǎn)換
  • map轉(zhuǎn)換的時候,key必須為string
  • 封裝的時候,如果是指針,會追蹤指針指向的對象進行封裝

例如:

有一個struct結(jié)構:

type Post struct {
	Id      int
	Content string
	Author  string
}

這個結(jié)構表示博客文章類型,有文章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é)構都能解析成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輔助構建json

struct能被轉(zhuǎn)換的字段都是首字母大寫的字段,但如果想要在json中使用小寫字母開頭的key,可以使用struct的tag來輔助反射。

例如,Post結(jié)構增加一個首字母小寫的字段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的時候,幾個注意點:

  • tag中標識的名稱將稱為json數(shù)據(jù)中key的值
  • tag可以設置為`json:"-"`來表示本字段不轉(zhuǎn)換為json數(shù)據(jù),即使這個字段名首字母大寫
    • 如果想要json key的名稱為字符"-",則可以特殊處理`json:"-,"`,也就是加上一個逗號
  • 如果tag中帶有,omitempty選項,那么如果這個字段的值為0值,即false、0、""、nil等,這個字段將不會轉(zhuǎn)換到json中
  • 如果字段的類型為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é)構已知)

json數(shù)據(jù)可以解析到struct或空接口interface{}中(也可以是slice、map等)。理解了上面構建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ù):

  • 頂層的大括號表示是一個匿名對象,映射到Go中是一個struct,假設這個struct名稱為Post
  • 頂層大括號里的都是Post結(jié)構中的字段,這些字段因為都是json數(shù)據(jù),所以必須都首字母大寫,同時設置tag,tag中的名稱小寫
  • 其中author是一個子對象,映射到Go中是另一個struct,在Post中這個字段的名稱為Author,假設名稱和struct名稱相同,也為Author
  • label是一個數(shù)組,映射到Go中可以是slice,也可以是array,且因為json array為空,所以Go中的slice/array類型不定,比如可以是int,可以是string,也可以是interface{},對于這里的示例來說,我們知道標簽肯定是string
  • nextPost是一個子對象,映射到Go中是一個struct,但因為json中這個對象為null,表示這個對象不存在,所以無法判斷映射到Go中struct的類型。但對此處的示例來說,是沒有下一篇文章,所以它的類型應該也是Post類型
  • comment是子對象,且是數(shù)組包圍的,映射到Go中,是一個slice/array,slice/array的類型是一個struct

分析之后,對應地去構建struct和struct的tag就很容易了。如下,是根據(jù)上面分析構建出來的數(shù)據(jù)結(jié)構:

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"` 
}

注意,前面在介紹構建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é)構的自動轉(zhuǎn)換工具。

解析json到interface(結(jié)構未知)

上面是已知json數(shù)據(jù)結(jié)構的解析方式,如果json結(jié)構是未知的或者結(jié)構可能會發(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é)構。這是顯然的,因為類型對應關系中已經(jīng)說明了,json object解析到Go interface的時候,對應的是map結(jié)構。如果將上面輸出的結(jié)構進行一下格式化,得到的將是類似下面的結(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:[]
]

現(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é)構而導致無法正確迭代遍歷。這時候,可以使用第三方包simplejson,見后文。

解析、創(chuàng)建json流

除了可以直接解析、創(chuàng)建json數(shù)據(jù),還可以處理流式數(shù)據(jù)。

  • type Decoder解碼json到Go數(shù)據(jù)結(jié)構
  • type Encoder編碼Go數(shù)據(jù)結(jié)構到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)
        }
    }
}

json轉(zhuǎn)Go數(shù)據(jù)結(jié)構工具推薦

quicktype工具,可以輕松地將json文件轉(zhuǎn)換成各種語言對應的數(shù)據(jù)結(jié)構。

地址:https://quicktype.io

在vscode中有相關插件

  • 先在命令面板中輸入"set quicktype target language"選擇要將json轉(zhuǎn)換成什么語言的數(shù)據(jù)結(jié)構(比如Go)
  • 再輸入"open quicktype for json"就可以將當前json文件轉(zhuǎn)換對應的數(shù)據(jù)結(jié)構(比如struct)

轉(zhuǎn)換后只需按實際的需求稍微修改一部分類型即可。比如為json頂級匿名對象對應的struct設定名稱,還有一些無法轉(zhuǎn)換成struct時因為判斷數(shù)據(jù)類型而使用的interface{}類型也要改一改。

例如,下面是使用quicktype工具對前面示例json數(shù)據(jù)進行轉(zhuǎn)換后的數(shù)據(jù)結(jié)構:

type A struct {
	ID        int64         `json:"id"`       
	Content   string        `json:"content"`  
	Author    Author        `json:"author"`   
	Published bool          `json:"published"`
	Label     []interface{} `json:"label"`    
	NextPost  interface{}   `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"` 
}

其中需要將type A struct的A改成你自己的名稱,將A中的interface{}也改成合理的類型。

更多關于Go處理json數(shù)據(jù)方法請查看下面的相關鏈接

相關文章

  • golang中json和struct的使用說明

    golang中json和struct的使用說明

    這篇文章主要介紹了golang中json和struct的使用說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-05-05
  • Golang?Gin框架獲取請求參數(shù)的幾種常見方式

    Golang?Gin框架獲取請求參數(shù)的幾種常見方式

    在我們平常添加路由處理函數(shù)之后,就可以在路由處理函數(shù)中編寫業(yè)務處理代碼了,但在此之前我們往往需要獲取請求參數(shù),本文就詳細的講解下gin獲取請求參數(shù)常見的幾種方式,需要的朋友可以參考下
    2024-02-02
  • zap接收gin框架默認的日志并配置日志歸檔示例

    zap接收gin框架默認的日志并配置日志歸檔示例

    本文介紹了在基于gin框架開發(fā)的項目中如何配置并使用zap來接收并記錄gin框架默認的日志和如何配置日志歸檔。有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2022-04-04
  • GoFrame框架數(shù)據(jù)校驗之校驗對象校驗結(jié)構體

    GoFrame框架數(shù)據(jù)校驗之校驗對象校驗結(jié)構體

    這篇文章主要為大家介紹了GoFrame框架數(shù)據(jù)校驗之校驗對象校驗結(jié)構體示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-06-06
  • Go語言中關于set的實現(xiàn)思考分析

    Go語言中關于set的實現(xiàn)思考分析

    Go?開發(fā)過程中有時我們需要集合(set)這種容器,但?Go?本身未內(nèi)置這種數(shù)據(jù)容器,故常常我們需要自己實現(xiàn),下面我們就來看看具體有哪些實現(xiàn)方法吧
    2024-01-01
  • OpenTelemetry-go的SDK使用方法詳解

    OpenTelemetry-go的SDK使用方法詳解

    這篇文章主要介紹了OpenTelemetry-go的SDK使用方法,OpenTelemetry幫我們實現(xiàn)了相應語言的SDK,所以我們只需要進行調(diào)用即可,本文根據(jù)官方文檔實例講解,需要的朋友可以參考下
    2022-09-09
  • Golang爬蟲框架 colly的使用

    Golang爬蟲框架 colly的使用

    本文主要介紹了Golang爬蟲框架 colly的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-07-07
  • Go語言:打造優(yōu)雅數(shù)據(jù)庫單元測試的實戰(zhàn)指南

    Go語言:打造優(yōu)雅數(shù)據(jù)庫單元測試的實戰(zhàn)指南

    Go語言數(shù)據(jù)庫單元測試入門:聚焦高效、可靠的數(shù)據(jù)庫代碼驗證!想要確保您的Go應用數(shù)據(jù)層堅如磐石嗎?本指南將手把手教您如何利用Go進行數(shù)據(jù)庫單元測試,輕松揪出隱藏的bug,打造無懈可擊的數(shù)據(jù)處理邏輯,一起來探索吧!
    2024-01-01
  • 一文帶你學會Go?select語句輕松實現(xiàn)高效并發(fā)

    一文帶你學會Go?select語句輕松實現(xiàn)高效并發(fā)

    這篇文章主要為大家詳細介紹了Golang中select語句的用法,文中的示例代碼講解詳細,對我們學習Golang有一定的幫助,需要的可以參考一下
    2023-03-03
  • golang并發(fā)編程的實現(xiàn)

    golang并發(fā)編程的實現(xiàn)

    這篇文章主要介紹了golang并發(fā)編程的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-01-01

最新評論