Golang中JSON的使用

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

GO Json

author: qcliu
date: 2015/07/21

Abstrct

介紹go語言中json的使用

json

json是一種傳輸格式,類似與XML,與XML相比可讀性略差,但是傳輸效率高。

GO Json

go語言中提供了json的encoder,可以將資料結構轉換為json格式。在使用之前,需要匯入包

import "encoding/json"

Encode

使用

func NewEncoder(w io.Writer) *Encoder

建立一個json的encode。

file, _ := os.Create("json.txt")enc := json.NewEncoder(file)err := enc.Encode(&v)

資料結構v會以json格式寫入json.txt檔案。

Decode

使用

func NewDecoder(r io.Reader) *Decoder

建立一個json的decode。

fp, _ os.Open("json.txt")dec := json.NewDecoder(fp)for {    var V v    err := dec.Decode(&v)    if err != nil {        break    }    //use v}

v是一個資料結構空間,decoder會將檔案中的json格式按照v的定義轉化,存在v中。

Example

type Person struct {    name string    age int}type Student struct {    p *Person    sno int}

對於Student類型,雖然裡面有一個指標,gojson一樣可以處理。在encode與decode時,會自動的遞迴下降的進行格式轉換。

Summary

  • encoder與decoder像是在writer外面封裝了一層。會根據指定的資料結構的格式進行讀寫。如果檔案中的json格式與指定的資料結構的格式不一致會出現error。
  • 在decoder的過程中,用一個for{}不停的讀檔案,直到出現error,代表檔案結束。在for{}中,每次都要申請一個新的空間,存放從檔案中讀取出來的資料。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.