introduction
In Go, we can useencoding/json
andencoding/xml
Packages to process JSON and XML data.
Processing JSON data
Here is a simple example that shows how to usejson
Packet encoding and decoding JSON data:
package main import ( "encoding/json" "fmt" ) type Person struct { Name string `json:"name"` Age int `json:"age"` } func main() { // Encoding JSON person := Person{Name: "Alice", Age: 20} bytes, _ := (person) (string(bytes)) // Output: {"name":"Alice","age":20} // Decode JSON var p Person (bytes, &p) (p) // Output: {Alice 20}}
In this example, we first define aPerson
Type, it hasName
andAge
Two fields. Then, we created aPerson
Object, and useThe function encodes it as JSON. Finally, we use
Function decodes JSON data into
Person
Object.
Process XML data
The way XML data is processed is similar to JSON data. Here is a simple example:
package main import ( "encoding/xml" "fmt" ) type Person struct { Name string `xml:"name"` Age int `xml:"age"` } func main() { // Encoding XML person := Person{Name: "Alice", Age: 20} bytes, _ := (person) (string(bytes)) // Output: <Person><name>Alice</name><age>20</age></Person> // Decode XML var p Person (bytes, &p) (p) // Output: {Alice 20}}
In this example, we useand
Functions to encode and decode XML.
Note that in general, we need to deal with errors, and here we ignore error handling to simplify the example.
This is the basic way to handle JSON and XML data in Go. You can use more complex data structures as needed to process more complex JSON and XML data.
The above is the detailed content of go language processing JSON and XML data. For more information about go language processing data, please pay attention to my other related articles!