JSON and Go__json

Source: Internet
Author: User
Tags data structures
introduce

JSON (JavaScript Object notation) is a simple format for data interchange. Syntactically, it combines JavaScript objects (objects) and lists (lists). Typically used to communicate between the Web backend and JavaScript programs that run in the browser, but can also be used in many other places. The official homepage, json.org, provides a detailed description of the standards.

Using the JSON package makes it easy to read and write JSON data encoding in the GO program

Encodes JSON data through function marshal.

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

Given Go's data structure, message,

Type message struct {
    Name string body
    string time
    Int64
}

And an instance of the message

M: = message{"Alice", "Hello", 1294706395881547000}

Through JSON. Marshal can get a JSON-formatted m:

B, err: = json. Marshal (M)

If everything goes well, err will be nil,b. will be a []byte that contains JSON data:

b = = []byte (' {' Name]: "Alice", "Body": "Hello", "Time": 1294706395881547000} ')

Only data that can be represented as valid JSON is encoded: JSON objects only supports strings as keys; to encode the go map type, it must be this is the form map[string]t (where T any one of the JSON packages supports the go type) Channel, c Omplex and functions cannot be encoded and do not support cyclic data structures; This causes Marshal to go into the dead loop pointers are encoded into the values they point to (or null if the pointer is nil) to decode

Decodes JSON data via function Unmarshal.

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

First, declare a variable for storing the decoded data

VAR m message

Then call JSON. Unmarshal, passing parameter JSON data []byte and pointers to M

ERR: = json. Unmarshal (b, &m)

If B contains a valid JSON that matches m, then after the function call, the data in the ERR value nil,b is stored in the structure m, as in the following assignment:

m = message{
    Name: "Alice", Body
    : "Hello",
    time:1294706395881547000,
}

How does Unmarshal define the data that is stored in the decoding? For a given JSON key "foo", Unmarshal queries the domain of the struct to find (in order of preference): An exportable field with the tag "foo" (more about the structure tag see go spec) A exportable field named "foo" , or an exportable field named "foo" or "foo" or other case-matching "foo"

What happens when the JSON data structure is inconsistent with the go type?

B: = []byte (' {' Name ': ' Bob ', ' Food ': ' Pickle '} ')
var m message
Err: = json. Unmarshal (b, &m)

Unmarshal only decodes fields that appear in the target type. In the example above, only the name field will be populated, and the food field will be ignored. This behavior is especially useful when you want to select several specified domains from a large JSON blob. This also means that Unmarshal does not affect the non-exportable domain in the target structure body.

But what if you didn't know the structure of the JSON data beforehand? Generic JSON with interface{}

The interface{} type (an empty interface) represents an interface with no methods. Each go type implements at least 0 methods and therefore conforms to the null interface.

The null interface can be used as a generic container type:

var i interface{}
i = "a string" i = i =
2.777

Type assertions can access the underlying concrete types:

R: = I. (float64)
FMT. Println ("The Circle ' s area", Math.) PI*R*R)

Alternatively, if the underlying type is unknown, type switch is used to determine the type:

Switch V: = I. (type) {case
int:
    FMT. Println ("Twice I are", v*2) case
float64:
    fmt. PRINTLN ("The reciprocal of I is", 1/v) Case
string:
    h: = Len (v)/2
    FMT. PRINTLN ("I swapped by halves is", v[h:]+v[:h])
default:
    //I isn ' one of the types above
}

The JSON package uses map[string]interface{} and []interface{} to store any JSON objects and arrays; it is happy to unmarshal any legitimate JSON blob to the normal interface {}. The default specific go type is: BOOL JSON booleans float64 JSON numbers string JSON strings nil JSON null decode arbitrary data

Consider such a JSON data stored in variable B:

B: = []byte (' {"Name ':" Wednesday "," Age ": 6," Parents ": [" Gomez "," Morticia "]}")

When you do not know the data structure, we can unmarshal it to interface{}:

var f interface{}
err: = json. Unmarshal (b, &f)

Now the value in F is a map,key to a string, and the value is itself stored as an empty interface:

f = map[string]interface{}{
    "Name": "Wednesday",
    "age":  6,
    "Parents": []interface{}{

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.