author: qcliu
date: 2015/07/21json
介紹go語言中json的使用數據結構
json是一種傳輸格式,相似與XML,與XML相比可讀性略差,可是傳輸效率高。指針
go語言中提供了json的encoder,能夠將數據結構轉換爲json格式。在使用以前,須要導入包code
import "encoding/json"
使用遞歸
func NewEncoder(w io.Writer) *Encoder
建立一個json的encode。string
file, _ := os.Create("json.txt") enc := json.NewEncoder(file) err := enc.Encode(&v)
數據結構v會以json格式寫入json.txt
文件。it
使用io
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中。import
type Person struct { name string age int } type Student struct { p *Person sno int }
對於Student類型,雖然裏面有一個指針,gojson同樣能夠處理。在encode與decode時,會自動的遞歸降低的進行格式轉換。