1. 程式人生 > >Go處理json資料

Go處理json資料

json資料格式

參見json資料格式說明

如果沒操作過json資料,建議先看下上面的文章,有助於理解本文後面的內容。

Go json包

Marshal():Go資料物件 -> json資料
UnMarshal():Json資料 -> Go資料物件

func Marshal(v interface{}) ([]byte, error)
func Unmarshal(data []byte, v interface{}) error

構建json資料

Marshal()和MarshalIndent()函式可以將資料封裝成json資料。

  • struct、slice、array、map都可以轉換成json

  • struct轉換成json的時候,只有欄位首字母大寫的才會被轉換
  • map轉換的時候,key必須為string
  • 封裝的時候,如果是指標,會追蹤指標指向的物件進行封裝

例如:

有一個struct結構:

type Post struct {
    Id      int
    Content string
    Author  string
}

這個結構表示部落格文章型別,有文章ID,文章內容,文章的提交作者。這沒什麼可說的,唯一需要指明的是:它是一個struct,struct可以封裝(編碼)成JSON資料

要將這段struct資料轉換成json,只需使用Marshal()即可。如下:

post := &Post{1, "Hello World", "userA"}
b, err := json.Marshal(post)
if err != nil {
    fmt.Println(nil)
}

Marshal()返回的是一個[]byte型別,現在變數b就已經儲存了一段[]byte型別的json資料,可以輸出它:

fmt.Println(string(b))

結果:

{"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))

結果:

{
    "Id": 1,
    "Content": "Hello World",
    "Author": "userA"
}

除了struct,array、slice、map結構都能解析成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))

返回結果:

[
    "a",
    "b",
    "c"
]
{
    "a": "aa",
    "b": "bb",
    "c": "cc"
}

使用struct tag輔助構建json

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

例如,Post結構增加一個首字母小寫的欄位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))

結果:

{
    "ID": 2,
    "content": "Hello World",
    "author": "userB",
    "label": [
        "linux",
        "shell"
    ]
}

使用struct tag的時候,幾個注意點:

  1. tag中標識的名稱將稱為json資料中key的值
  2. tag可以設定為`json:"-"`來表示本欄位不轉換為json資料,即使這個欄位名首字母大寫
    • 如果想要json key的名稱為字元"-",則可以特殊處理`json:"-,"`,也就是加上一個逗號
  3. 如果tag中帶有,omitempty選項,那麼如果這個欄位的值為0值,即false、0、""、nil等,這個欄位將不會轉換到json中
  4. 如果欄位的型別為bool、string、int類、float類,而tag中又帶有,string選項,那麼這個欄位的值將轉換成json字串

例如:

type Post struct {
    Id      int      `json:"ID,string"`
    Content string   `json:"content"`
    Author  string   `json:"author"`
    Label   []string `json:"label,omitempty"`
}

解析json資料到struct(結構已知)

json資料可以解析到struct或空介面interface{}中(也可以是slice、map等)。理解了上面構建json時的tag規則,理解解析json就很簡單了。

例如,下面是一段json資料:

{
    "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資料:

  1. 頂層的大括號表示是一個匿名物件,對映到Go中是一個struct,假設這個struct名稱為Post
  2. 頂層大括號裡的都是Post結構中的欄位,這些欄位因為都是json資料,所以必須都首字母大寫,同時設定tag,tag中的名稱小寫
  3. 其中author是一個子物件,對映到Go中是另一個struct,在Post中這個欄位的名稱為Author,假設名稱和struct名稱相同,也為Author
  4. label是一個數組,對映到Go中可以是slice,也可以是array,且因為json array為空,所以Go中的slice/array型別不定,比如可以是int,可以是string,也可以是interface{},對於這裡的示例來說,我們知道標籤肯定是string
  5. nextPost是一個子物件,對映到Go中是一個struct,但因為json中這個物件為null,表示這個物件不存在,所以無法判斷對映到Go中struct的型別。但對此處的示例來說,是沒有下一篇文章,所以它的型別應該也是Post型別
  6. comment是子物件,且是陣列包圍的,對映到Go中,是一個slice/array,slice/array的型別是一個struct

分析之後,對應地去構建struct和struct的tag就很容易了。如下,是根據上面分析構建出來的資料結構:

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資料的時候說明過,指標會進行追蹤,所以這裡反推出來的struct中使用指標型別是沒問題的。

於是,解析上面的json資料到Post型別的物件中,假設這個json資料存放在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資料到post中
    err = json.Unmarshal(jsonData, &post)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(post)
}

輸出結果:

{1 hello world {2 userA} true [] <nil> [0xc042072300 0xc0420723c0]}

也許你已經感受到了,從json資料反推算struct到底有多複雜,雖然邏輯不難,但如果資料複雜一點,這是件非常噁心的事情。所以,使用別人寫好的工具來自動轉換吧。本文後面有推薦json到資料結構的自動轉換工具。

解析json到interface(結構未知)

上面是已知json資料結構的解析方式,如果json結構是未知的或者結構可能會發生改變的情況,則解析到struct是不合理的。這時可以解析到空介面interface{}map[string]interface{}型別上,這兩種型別的結果是完全一致的。

解析到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資料
    var unknown interface{}
    // 或:map[string]interface{} 結果是完全一樣的
    err = json.Unmarshal(jsonData, &unknown)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(unknown)
}

輸出結果:

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結構。這是顯然的,因為型別對應關係中已經說明了,json object解析到Go interface的時候,對應的是map結構。如果將上面輸出的結構進行一下格式化,得到的將是類似下面的結構:

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中去判斷型別、取得對應的值。但是如何判斷型別?可以使用型別斷言:

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資料到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("------------------")
        }
    }
}

結果如下:

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中解析非常複雜,而且可能因為巢狀結構而導致無法正確迭代遍歷。這時候,可以使用第三方包simplejson,見後文。

解析、建立json流

除了可以直接解析、建立json資料,還可以處理流式資料。

  • type Decoder解碼json到Go資料結構
  • type Encoder編碼Go資料結構到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資料,解碼後刪除名為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轉Go資料結構工具推薦

quicktype工具,可以輕鬆地將json檔案轉換成各種語言對應的資料結構。

地址:https://quicktype.io

在vscode中有相關外掛

  1. 先在命令面板中輸入"set quicktype target language"選擇要將json轉換成什麼語言的資料結構(比如Go)
  2. 再輸入"open quicktype for json"就可以將當前json檔案轉換對應的資料結構(比如struct)

轉換後只需按實際的需求稍微修改一部分型別即可。比如為json頂級匿名物件對應的struct設定名稱,還有一些無法轉換成struct時因為判斷資料型別而使用的interface{}型別也要改一改。

例如,下面是使用quicktype工具對前面示例json資料進行轉換後的資料結構:

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{}也改成合理的型別。