This is a creation in Article, where the information may have evolved or changed. JSON (Javascript Object Notation) is a lightweight data exchange language that is text-based, self-descriptive and easy to read. Although JSON is a subset of JavaScript, JSON is a language-independent text format and uses some of the same habits as the C language family. The biggest difference between JSON and XML is that XML is a complete markup language, and JSON is not. JSON is smaller, faster, easier to parse than XML, and the browser's built-in fast parsing support makes it more suitable for network data transmission.
Parse to struct the JSON package for Go has the following function
Json.gopackage mainimport ("Encoding/json" "FMT") type Server struct {ServerName Stringserverip string}type serverslice struct {Servers []server}func main () {var s serverslicestr: = ' {"Servers": [{"ServerName": "Shanghai_vpn", " ServerIP ":" 127.0.0.1 "},{" ServerName ":" Beijing_vpn "," ServerIP ":" 127.0.0.2 "}]} ' JSON. Unmarshal ([]byte (str), &s) fmt. Println (s) fmt. Println (S.servers[0]. ServerIP)}
Outputs: {[{Shanghai_vpn 127.0.0.1} {Beijing_vpn 127.0.0.2}]} 127.0.0.1 First, we define the structure corresponding to the JSON data, the array corresponds to the slice, the field name corresponds to the key in the JSON, how to match the JSON data with the struct field when parsing? If the JSON key is Foo, then how to find the corresponding field?
- First, look for the exportable struct field with the tag foo (first capitalization)
- Second, find the field name is Foo's export field
- Finally look for an export field such as Foo or foo that is not sensitive to case except the first letter
the field that can be assigned must be an exportable field (that is, the first letter capitalized). At the same time, the JSON parsing will only parse the fields that can be found, if the missing fields are ignored, one of the benefits is that when you receive a large JSON data structure and you just want to get some of the data, you can easily solve the problem by capitalizing the field name of the data you want.
parsing to interface we know that interface{} can be used to store objects of any data type, which is exactly the result of storing JSON data for an unknown structure that is parsed. The JSON package uses map[string]interface{} and the []interface{} structure to store any JSON objects and arrays. The corresponding relationship between the go type and the JSON type is as follows:
- BOOL stands for JSON Booleans
- Float64 on behalf of JSON numbers
- String represents the JSON strings
access the data by asserting, as in the following example:
Tointer.gopackage mainimport ("Encoding/json" "FMT") func main () {b: = []byte (' {"Name": "Wednesday", "Age": 6, "parents" : ["Gomez", "Moticia"]} ') var f interface{}err: = json. Unmarshal (b, &f) if err! = Nil {fmt. PRINTLN (err)}m: = f. (map[string]interface{}) for k, V: = range m {Switch VV: = V. (type) {case string:fmt. Println (k, ' is String ', vv) case int:fmt. Println (K, "is Int.", VV) case []INTERFACE{}:FMT. Println (K, "is a array:") for I, U: = Range VV {fmt. Println (i, u)}default:fmt. Println (K, "is of a type I don ' t know how to Handle")}}
Outputs: Name is string Wednesday Age was of a type I don ' t know how to handle parents is an array: 0 Gomez 1 Moticia As you can see from the example above, we can parse the JSON function of the unknown structure by interface{} with the type Assert. Generate JSON if we want to output a JSON data string, we can use the marshal function to handle
Func Marshal (v interface{}) ([]byte, error)
Example:
Generaljsonpackage mainimport ("Encoding/json" "FMT") type Server struct {ServerName string ' JSON: ' ServerName ' ServerIP string ' JSON: ' ServerIP ' '}type serverslice struct {Servers []server ' JSON: ' Servers ' '}func main () {var s Serverslices.servers = Append (S.servers, server{servername: "Shanghai_vpn", ServerIP: "127.0.0.1"}) S.servers = append ( S.servers, Server{servername: "Beijing_vpn", ServerIP: "127.0.0.2"}) b, err: = json. Marshal (s) if err! = Nil {fmt. PRINTLN ("JSON err:", err)}fmt. Println (string (b))}
Outputs: {"Servers": [{"ServerName": "Shanghai_vpn", "ServerIP": "127.0.0.1"}, {"ServerName": "Beijing_vpn", "ServerIP": " 127.0.0.2 "}]} for JSON output, we need to be aware of several points when defining a struct tag:
- The field tag is "-", then this field is not output to JSON
- With a custom name in the tag, the custom name appears in the field name of the JSON, such as the ServerName in the example above
- If there is a "omitempty" option in the tag, then if the field value is empty, it will not be exported to the JSON string.
- If the field type is Bool,string,int,int64, and the tag has a "string" option, the field will convert the value of the field to a JSON string when it is output to JSON.
Example:
Jsontest.gopackage mainimport ("Encoding/json" "OS") type Server struct {//id will not be exported to Jsonid int ' JSON: "-" '// The value of ServerName is two times JSON encoded serverName string ' JSON: "ServerName" ' ServerName2 string ' JSON: "ServerName2, String" '// If ServerIP is empty, it is not exported to JSON ServerIP string ' JSON: "Serverip,omitempty" ' Description string ' JSON: "Description, String "'}func main () {s: = Server{id: 3,servername: ' Go ' 1.0" ', ServerName2: ' Go ' 1.0 "', ServerIP: ', Description: ' Description information ',}b, _: = json. Marshal (s) os. Stdout.write (b)}
Outputs: {"ServerName": "Go \" 1.0\ "", "serverName2": "Go \" 1.0\ ""} The marshal function only returns data when the conversion is successful, and we need to note several points during the conversion process:
- The JSON object only supports string as key, so to encode a map, it must be a type map[string]t (T is any type in the Go language)
- Channel,complex and function cannot be encoded into JSON.
- Nested data cannot be encoded, otherwise JSON encoding goes into a dead loop
- The pointer outputs the contents of the pointer as it is encoded, and the null pointer outputs null
at present bitly company Open source A package called Simplejson, in dealing with the unknown structure of JSON is quite convenient, address:Https://github.com/bitly/go-simplejson