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".