Use of JSON in Golang

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.