Using JSON in the Go language

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

Encode

Encodes an object into JSON data, accepts a interface{} object, and returns []byte and Error:

Func Marshal (v interface{}) ([]byte, error)

The marshal function recursively iterates through the entire object, encodes the object by member type, and the type conversion rule is as follows:

BOOL Type conversion to JSON
Integer, floating-point number, and other numeric types converted to JSON numbers
String converted to JSON (with "" quotation marks)
struct is converted to JSON object and then recursively packaged according to the type of each member
Array or slice converted to JSON
[]byte will first base64 encode and then convert to a JSON string
The Object,key map converted to JSON must be a string
interface{} converted according to the actual type inside
Nil converted to JSON null
Channel,func and other types will return Unsupportedtypeerror

Type Colorgroup struct {    id     int    Name   string    Colors []string}group: = colorgroup{    ID:     1,    Name:   "Reds",    Colors: []string{"Crimson", "Red", "Ruby", "maroon"},}b, err: = json. Marshal (group) if err! = Nil {    FMT. Println ("Error:", err)}os. Stdout.write (b) output:{"ID": 1, "Name": "Reds", "Colors": ["Crimson", "Red", "Ruby", "Maroon"]}

Decode

Decoding the JSON data

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

Type conversion rules are similar to the above rules

var jsonblob = []byte (' [    {] ' name ': "Platypus", "Order": "Monotremata"},    {"name": "Quoll",    "order": " Dasyuromorphia "}] ') type Animal struct {    Name  string    Order string}var animals []animalerr: = json. Unmarshal (Jsonblob, &animals) if err! = Nil {    FMT. Println ("Error:", err)}fmt. Printf ("%+v", Animals) Output:[{name:platypus Order:monotremata} {name:quoll Order:dasyuromorphia}]

Structural body

The struct must be a member of the beginning of the uppercase letter to be processed by the JSON, and the members beginning with the lowercase letter will not be affected.

When Mashal, the member variable name of the struct will be packaged directly as a key of the JSON object, and will automatically match the corresponding variable names for assignment, which is not case sensitive.

Unmarshal, if there are extra fields in the JSON, it will be discarded directly, if the JSON is missing a field, then directly ignore the variable assignment in the struct, without error.

Type Message struct {Name  stringbody  stringtime  int64inner string}var m = message{name:  "Alice", Body:  "Hello", Time:  1294706395881547000,inner: "OK",}b: = []byte (' {"NAmE": "Bob", "Food": "Pickle", "inner": " Changed "}") Err: = json. Unmarshal (b, &m) if err! = Nil {fmt. Printf (Err. Error ()) return}fmt. Printf ("%v", m) output:{bob Hello 1294706395881547000 OK}

Structtag

If you want to manually configure the corresponding relationship between the members of the struct and the JSON field, you can label the members when you define the structure body:

With Omitempty, if the field is nil or 0 values (the number 0, the string "", the empty array [], and so on), then the wrapped JSON result will not have this fields.

Type Message struct {Name string ' JSON: ' msg_name '///Msg_namebody string ' JSON for JSON: ' body,omitempty '///if empty, ignore Field time Int64 ' JSON: "-" '///Direct Ignore field}var m = message{name: "Alice", Body: ", Time:1294706395881547000,}data, er r: = json. Marshal (m) if err! = Nil {fmt. Printf (Err. Error ()) return}fmt. PRINTLN (String data) output:{"Msg_name": "Alice"}

More flexibility in using JSON

Use JSON. Rawmessage

Json. Rawmessage is actually a redefinition of the []byte type. You can make a forced type conversion.

There is now a scenario in which the format of one of the fields in the struct is unknown:

Type Command struct {ID   intcmd  Stringargs *json. Rawmessage}

Use JSON. Rawmessage, the args field is not parsed at Unmarshal, and the byte data is assigned to args directly. We can first unpack the first layer of JSON data, and then determine the specific type of args for the second Unmarshal, based on the value of CMD.

It is important to note that you must use the pointer type *json. Rawmessage, otherwise the args are considered to be []byte types, which are packaged as Base64 encoded strings when packaged.

Use interface{}

interface{} When the type is Unmarshal, JSON is automatically converted to the corresponding data type:

Boolean conversion of JSON to BOOL
The value of JSON is converted to float64
JSON strings converted to string
The JSON array is converted to []interface{}
JSON object converted to map[string]interface{}
JSON null converted to nil

There are two needs to be aware of. One is that all JSON values are automatically converted to the Float64 type, which needs to be manually converted to the desired int,int64 type. The second is that the JSON object is automatically converted to the map[string]interface{} type, accessed directly using the field name of the JSON object as key. If you do not know the format of the JSON data, you can use interface{}.

Custom Types

You can implement the following interfaces if you want to define your own package unpacking methods:

Type Marshaler Interface {    Marshaljson () ([]byte, error)}type Unmarshaler interface {    Unmarshaljson ([]byte) Error

Objects that implement this interface need to package and package their own data. If the interface is implemented, JSON will call a custom method when unpacking the package, and no more processing of the object.


Related Article

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.