This is a creation in Article, where the information may have evolved or changed.
GO Json
Author:qcliu
Date:2015/07/21
Abstrct
Introducing the use of JSON in the Go language
Json
JSON is a transport format, similar to XML, which is slightly less readable than XML, but has a high transmission efficiency.
GO Json
The encoder of JSON is provided in the go language to convert the data structure to JSON format. Before you use it, you need to import the package
import "encoding/json"
Encode
Use
func NewEncoder(w io.Writer) *Encoder
Create a JSON encode.
file, _ := os.Create("json.txt")enc := json.NewEncoder(file)err := enc.Encode(&v)
Data structure v is written to the file in JSON format json.txt .
Decode
Use
func NewDecoder(r io.Reader) *Decoder
Create a 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 is a data structure space where decoder converts the JSON format in the file to the definition of V, which is present in V.
Example
type Person struct { name string age int}type Student struct { p *Person sno int}
For the student type, although there is a pointer inside, Gojson can handle the same. In encode and decode, the recursive descent is automatically converted to format.
Summary
- Encoder and decoder like a layer in the outer envelope of writer. Reads and writes according to the format of the specified data structure. Error occurs if the JSON format in the file is inconsistent with the format of the specified data structure.
- In the decoder process, with a for{} read the file continuously until error occurs, representing the end of the file. In for{}, each time a new space is requested to hold the data read from the file.