Bad news travels fast while good news stays indoors
Programming languages, to some extent, are born to facilitate the operation of data. In real life, for various reasons, data are artificially divided into categories according to different formats. For each type of data, the processing methods are also different, and it is impossible to cover all types of data. This article focuses on XML and JSON, two high-frequency data types.
Parsing XML data
/* <? The XML version = "1.0" encoding = "utf-8"? > < Servers version="1"> <server> <serverName>Shanghai_VPN</serverName> <serverIP>127.0.0.1</serverIP> </server> <server> <serverName>Beijing_VPN</serverName> <serverIP>127.0.0.2</serverIP> </server> </ Servers > */ // / XML data parsing /* type Recurlyservers struct { XMLName xml.Name `xml:"servers"` Version string `xml:"version,attr"` Svs []server `xml:"server"` Description string `xml:"innerxml"` } type server struct { XMLName xml.Name `xml:"server"` ServerName string `xml:"serverName"` ServerIP string `xml:"serverIP"` } func main() { file, err := os.Open("servers.xml") if err ! = nil { fmt.Printf("error:%v", err) return } defer file.Close() data, err := ioutil.ReadAll(file) if err ! = nil { fmt.Printf("error: %v", err) return } v := Recurlyservers{} err = xml.Unmarshal(data, &v) if err ! = nil { fmt.Printf("error:%v", Err) return} fmt.println (v)} */ // XML file generated /* type Servers struct {XMLName xml.Name 'XML :" Servers "' Version string `xml:version, attr` Svs []server `xml:"server"` } type server struct { ServerName string `xml:"serverName"` ServerIP string `xml:"serverIP"` } func main() { v := &Servers{Version: "1"} v.svs = append(v.svs, server{"Shanghai_VPN", "127.0.0.1"}) v.svs = append(v.svs, server{"Beijing_VPN", "127.0.0.1"}) output, err := XML.MarshalIndent(v, "", "") if err! = nil { fmt.Printf("error:%v\n", err) } os.Stdout.Write([]byte(xml.Header)) os.Stdout.Write(output) } */Copy the code
Json data parsing
/* Type Server struct {ServerName string ServerIP string} type Serverslice struct {Servers []Server} func main() { var s Serverslice str := ` {" 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)} */ / func main() {b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`) var f interface{} json.Unmarshal(b, 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 float64: fmt.Println(k, "is float64", vv) case []interface{}: fmt.Println(k, "is an array:", vv) for i, u := range vv { fmt.Println(i, u) } default: fmt.Println(k, "Is of a type I don't know how to handle")}}} * * func main() {type FruitBasket struct { Name String Fruit []string Id int64 'json:"ref"' // Declaration of corresponding JSON key Created time. time} jsonData := [] Byte (' {"Name": "Standard", "Fruit": [ "Apple", "Banana", "Orange" ], "ref": 999, "Created": "2018-04-09T23:00:00Z" }`) var basket FruitBasket err := json.Unmarshal(jsonData, &basket) if err ! = nil { fmt.Println(err) return } fmt.Println(basket.Id, basket.Fruit, Basket. The Name, basket. Created)} * / / * / / parse the json data of an embedded object inside func main () {type Fruit struct {Name string ` json: "Name" ` PriceTag string `json:"PriceTag"` } type FruitBasket struct { Name string Fruit Fruit id int64 `json:"ref"` Created time.Time } jsonData := []byte(`{ "Name": "Standard", "Fruit" : {"Name": "Apple", "PriceTag": "$1"}, "ref": 999, "Created": "2018-04-09T23:00:00Z" }`) var basket FruitBasket err := json.Unmarshal(jsonData, &basket) if err ! = nil { fmt.Println(err) return } fmt.Println(basket.Created, basket.id, Func main() {type Fruit struct {Name string 'json:" Name "' PriceTag string `json:"PriceTag"` } type FruitBasket struct { Name string Fruit []Fruit Id int64 `json:"ref"` Created time.Time } jsonData := []byte(`{ "Name": "Standard", "Fruit" : [ { "Name": "Apple", "PriceTag": "$1" }, { "Name": "Pear", "PriceTag" : "$1.5"}], "ref" : 999, "Created" : "2018-04-09T23:00:00Z" }`) var basket FruitBasket err := json.Unmarshal(jsonData, &basket) if err ! = nil { fmt.Println(err) return } fmt.Println(basket.Created, basket.Id, Func main() {type Fruit struct {Name string 'json:"Name"' PriceTag string FruitBasket struct {Name string Fruit map[string]Fruit Id int64 'json:"ref"' // Declare the corresponding JSON key Created time.Time } jsonData := []byte(` { "Name": "Standard", "Fruit" : { "1": { "Name": "Apple", "PriceTag": "$1"}, "2" : {" Name ":" Pear ", "PriceTag" : "$1.5"}}, "ref" : 999, "Created" : "2018-04-09T23:00:00Z" }`) var basket FruitBasket err := json.Unmarshal(jsonData, &basket) if err ! = nil { fmt.Println(err) } for _, item := range basket.Fruit { fmt.Println(item.Name, Item.pricetag)}} */ // parse arrays and objects containing arbitrary levels /* func main() {jsonData := []byte(`{"Name":"Eve","Age":6,"Parents":["Alice","Bob"]}`) var v interface{} json.Unmarshal(jsonData, &v) data := v.(map[string]interface{}) for k, v := range data { switch v := v.(type) { case string: fmt.Println(k, v, "(string)") case float64: fmt.Println(k, v, "(float64)") case []interface{}: fmt.Println(k, "(array):") for i, u := range v { fmt.Println(" ", i, u) } default: fmt.Println(k, v, * Type Server struct {ServerName string ServerIP string} type Serverslice struct { Servers []Server } func main() { var s Serverslice s.Servers = append(s.Servers, Server{ServerName: "Shanghai_VPN", ServerIP: "127.0.0.1"}) s.severs = append(s.severs, 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)) // If the field you want to output is lowercase, //ServerName string 'json:" ServerName "' //ServerName2 string 'json:" ServerName2,string" // If you do not want the field to be exported to JSON, use lowercase letters or define the following format //ID int 'json:"-"'} */Copy the code
summary
XML and JSON formats are widely used, especially for JSON data processing, so this part of the content must be mastered.
Refer to the blog