Reading and Writing JSON in Golang (Taming the JSON Beast!)

JSON (JavaScript Object Notation) is the favorite format for data exchange—easy for humans to read, and even easier for computers to process. But how do we deal with it in Go? Well, buckle up because we’re about to dive into the world of encoding and decoding JSON in Go, and trust me, it’s easier than convincing your cat to stop knocking things off the table. 

Importing the JSON Package

Go has a built-in encoding/json package that makes handling JSON a breeze. You don’t need any external libraries—just pure Go magic!

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

Writing (Encoding) JSON to a File

Imagine you have some data that you want to save in a JSON file. Let’s write some Go code that serializes a struct into JSON and saves it.

Example: Writing JSON to a File

package main

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

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"}
    file, err := os.Create("user.json")
    if err != nil {
        fmt.Println("Error creating file:", err)
        return
    }
    defer file.Close()

    encoder := json.NewEncoder(file)
    err = encoder.Encode(user)
    if err != nil {
        fmt.Println("Error encoding JSON:", err)
        return
    }

    fmt.Println("JSON data successfully written to user.json")
}

Output (user.json file):

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

Boom! We just wrote JSON to a file.

Reading (Decoding) JSON from a File

Now let’s read that JSON file and decode it back into a Go struct.

Example: Reading JSON from a File

package main

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

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

func main() {
    file, err := os.Open("user.json")
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer file.Close()

    var user User
    decoder := json.NewDecoder(file)
    err = decoder.Decode(&user)
    if err != nil {
        fmt.Println("Error decoding JSON:", err)
        return
    }

    fmt.Println("User data loaded:", user)
}

Output:

User data loaded: {Alice 25 alice@example.com}

And just like that, we’ve successfully read and parsed JSON from a file! 

Reading and writing JSON in Go is straightforward and efficient with the encoding/json package. Now, go forth and handle JSON like a boss—whether it’s for APIs, config files, or just storing your list of favorite memes!

Post a Comment

0 Comments