The use of the Go language JSON

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

The use of the Go language JSON

As the innate high concurrency go language, often used for network transmission, the Go language provides us with JSON data encapsulation,

facilitates the exchange and resolution of data. Let's look at JSON usage in the go language. The code is most obvious.

Important functions

Func Marshal (v interface{}) ([]byte, error) encoded as JSON data

Func unmarshal (data []byte, v interface{}) Error decodes JSON data

Package Mainimport ("Encoding/json", "FMT") type test struct {Name string ' JSON: "Test_name" ' Age  int    ' JSON: "Test_ Age "' G    int    ' JSON:" Test_g "'//the outer layer here is not single quote}func main () {t: = test{name:" Bojie ", Age:  100,g:    1,// Note that there is also a comma}data, _: = json. Marshal (t) fmt. Println (data, string (data)) var t1 test_ = json. Unmarshal (data, &t1) FMT. Println (t1. Name) <span style= "font-family:arial, Helvetica, Sans-serif;" >}</span>



The above code output is as follows

[123 34 116 101 115 116 95 110 97 109 101 34 58 34 98 111 106 105 101 34 44 34 116 101 115 116 95 97 103 101 34 58 49 48 4 8 125]
{"Test_name": "Bojie", "Test_age": Bojie

Look at the output to know that data is []byte type.

Yes, careful to find out, why is the information of G not? That's because of the case, if the struct body name is lowercase, it is automatically

is ignored. JSON encapsulation is not done.

Well, the above is the JSON encoding and decoding of the struct.

So how do we read from the following string to the value of test_name?

{"Test_name": "Bojie", "Test_age": 100}

We can start by creating a map type such as VAR tmp map[string]string

And then

Json. Unmarshal (msg,&tmp);//msg is the above string, TMP is the map type

Then we can get the Bojie value by tmp["Test_name".


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.