Encoding and Decoding Data in Golang (Speak Fluent JSON, XML, and More!)

Go makes working with data formats super easy with built-in encoding and decoding support. Whether you’re working with JSON, XML, or even custom formats, you can transform data like a wizard.  Ready to master encoding and decoding in Go? Let’s go!

Encoding and Decoding JSON (The Internet’s Favorite Format)

Since JSON is everywhere, Go’s encoding/json package is your best friend for converting Go structs to JSON and vice versa.

Example: Encoding a Struct to JSON

package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}

func main() {
    user := User{Name: "Alice", Age: 25, Email: "alice@example.com"}
    jsonData, err := json.Marshal(user)
    if err != nil {
        fmt.Println("Error encoding JSON:", err)
        return
    }

    fmt.Println("Encoded JSON:", string(jsonData))
}

Output:

{"name":"Alice","age":25,"email":"alice@example.com"}

Boom! We just converted a Go struct into JSON. 

Example: Decoding JSON into a Struct

package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}

func main() {
    jsonData := `{"name":"Alice","age":25,"email":"alice@example.com"}`

    var user User
    err := json.Unmarshal([]byte(jsonData), &user)
    if err != nil {
        fmt.Println("Error decoding JSON:", err)
        return
    }

    fmt.Println("Decoded Struct:", user)
}

Output:

Decoded Struct: {Alice 25 alice@example.com}

Just like that, JSON is transformed back into a Go struct! 

Encoding and Decoding XML (Because Not Everything is JSON)

If you need to work with XML, Go’s encoding/xml package has your back.

Example: Encoding Struct to XML

package main

import (
    "encoding/xml"
    "fmt"
)

type User struct {
    XMLName xml.Name `xml:"user"`
    Name    string   `xml:"name"`
    Age     int      `xml:"age"`
    Email   string   `xml:"email"`
}

func main() {
    user := User{Name: "Alice", Age: 25, Email: "alice@example.com"}
    xmlData, err := xml.MarshalIndent(user, "", "  ")
    if err != nil {
        fmt.Println("Error encoding XML:", err)
        return
    }

    fmt.Println("Encoded XML:")
    fmt.Println(string(xmlData))
}

Output:

<user>
  <name>Alice</name>
  <age>25</age>
  <email>alice@example.com</email>
</user>

Nice and clean XML output!

Encoding and Decoding Custom Formats (When JSON and XML Aren’t Enough)

You can define your own encoding and decoding logic by implementing the MarshalJSON and UnmarshalJSON methods for your struct.

Example: Custom JSON Marshalling

package main

import (
    "encoding/json"
    "fmt"
    "strings"
)

type User struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
}

func (u User) MarshalJSON() ([]byte, error) {
    type Alias User
    return json.Marshal(&struct {
        Name string `json:"name"`
        Age  int    `json:"age"`
    }{
        Name: strings.ToUpper(u.Name), // Convert name to uppercase
        Age:  u.Age,
    })
}

func main() {
    user := User{Name: "Alice", Age: 25}
    jsonData, _ := json.Marshal(user)
    fmt.Println("Custom Encoded JSON:", string(jsonData))
}

Output:

{"name":"ALICE","age":25}

Custom encoding achieved! 

Encoding and decoding in Go is a breeze with built-in support for JSON, XML, and even custom formats. Now you can transform data with ease and impress your fellow devs! 

Post a Comment

0 Comments