Go language programming-json data processing

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

This article describes how to use the Go language library to convert objects to JSON format, and how to convert data in JSON format to objects

Convert an object to JSON-formatted data

The go language comes with a package that can be used to process data in JSON format
Package Import: Encoding/json
Function prototype: Func Marshal (v interface{}) ([]byte, error)
In the go language, to convert data to JSON format, you can use the Marshal function in the Encoding/json package for data conversion, the Marshal function can receive any type of parameter, after the conversion is complete, return the bytecode array and error information.
The specific source code in the Go language is as follows:

funcinterface{}) ([]byte, error) {    e := &encodeState{}    true})    ifnil {        returnnil, err    }    returnnil}

Here are the specific usage demos:

    • Create a structure
type Message struct {    Name string    Body string    Time int64}
    • converting data using the Marshal function
Message{"Alice""Hello"1294706395881547000}b, err := json.Marshal(m)

Parsing JSON data

To parse the JSON data, you can use the Unmarshal function in the Encoding/json package to parse the function prototype as follows:

funcUnmarshal(data []byte, v interface{}) error

Specifically, make the example:

    • First, you need to create a structure to store the transformed data
varMessage
    • Parsing JSON data
err := json.Unmarshal(b, &m)

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.