DEV Community

Romulo Gatto
Romulo Gatto

Posted on

Working with JSON and XML in Go

Working with JSON and XML in Go

JSON (JavaScript Object Notation) and XML (eXtensible Markup Language) are two popular data interchange formats used in various applications. Whether you're working on a web service, developing an API, or building any application that deals with data exchange, Go provides excellent support for both JSON and XML handling.

In this guide, we will explore how to work with JSON and XML in Go. We'll cover encoding and decoding data using these formats, as well as parsing and manipulating the structured data within them.

Encoding and Decoding JSON

Go makes it simple to encode structs or maps into JSON format by utilizing the built-in encoding/json package. To encode a struct/map into JSON, follow these steps:

  1. Create a struct or map containing your desired data fields.
  2. Import the encoding/json package.
  3. Use the json.Marshal() function to encode your struct/map into a byte slice representing the JSON object.

Here's an example illustrating how to encode a struct to JSON:

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name   string  `json:"name"`
    Age    int     `json:"age"`
    Emails []string  `json:"emails,omitempty"`
}

func main() {
    p := Person{Name: "John Doe", Age: 30}
    jsonBytes, err := json.Marshal(p)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    fmt.Println(string(jsonBytes))
}
Enter fullscreen mode Exit fullscreen mode

Decoding is equally straightforward; it involves unmarshaling the encoded bytes back into a variable of type struct/map using json.Unmarshal(). Here's an example:

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name   string  `json:"name"`
    Age    int     `json:"age"`
    Emails []string  `json:"emails,omitempty"`
}

func main() {
    jsonStr := `{"name":"John Doe","age":30}`
    var p Person

    err := json.Unmarshal([]byte(jsonStr), &p)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    fmt.Printf("%+v", p)
}
Enter fullscreen mode Exit fullscreen mode

Parsing and Manipulating XML

Go also provides a robust package called encoding/xml for parsing and manipulating XML data. This package allows you to easily navigate through the XML document, access tags, and attributes, and manipulate the underlying data.

To parse and work with an XML document in Go, follow these steps:

  1. Import the encoding/xml package.
  2. Create appropriate struct types that match your desired XML structure.
  3. Use the xml.Unmarshal() function to unmarshal the XML data into your defined struct variable.
  4. Access and manipulate the structured data within your struct variable.

Let's look at an example where we decode an XML string into a custom struct:

import (
    "encoding/xml"
    "fmt"
)

type City struct {
    Name     string   `xml:"name"`
    Country  string   `xml:"country"`
    Population int      `xml:"population"`
}

func main() {
    xmlStr :=
        `<city>
            <name>New York</name>
            <country>USA</country>
            <population>8622698</population>
        </city>`

    var c City

    err := xml.Unmarshal([]byte(xmlStr), &c)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    fmt.Printf("%+v", c)
}
Enter fullscreen mode Exit fullscreen mode

By defining appropriate struct fields with corresponding tags matching XML elements/attributes names, we can easily map our desired values from the parsed XML data.

Conclusion

Working with JSON and XML in Go is straightforward and efficient, thanks to the encoding/json package for JSON handling and the encoding/xml package for XML manipulation. With these capabilities, you can confidently encode, decode, parse, and manipulate structured data in your Go applications. So go ahead and leverage these powerful features while developing your next application!

Top comments (0)