SoFunction
Updated on 2025-03-05

Go language processing JSON and XML data example parsing

introduction

In Go, we can useencoding/jsonandencoding/xmlPackages to process JSON and XML data.

Processing JSON data

Here is a simple example that shows how to usejsonPacket 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 aPersonType, it hasNameandAgeTwo fields. Then, we created aPersonObject, and useThe function encodes it as JSON. Finally, we useFunction decodes JSON data intoPersonObject.

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, &amp;p)
    (p) // Output: {Alice 20}}

In this example, we useandFunctions 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!