encode object to json in go

To encode an object to JSON in Go, you can use the json.Marshal() function from the encoding/json package.

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

main.go
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    // Define a struct
    type Person struct {
        Name string
        Age  int
    }

    // Create a Person object
    p := Person{Name: "Alice", Age: 30}

    // Encode the Person object to JSON
    jsonBytes, err := json.Marshal(p)
    if err != nil {
        fmt.Println("Error encoding to JSON:", err)
        return
    }

    // Print the JSON string
    jsonString := string(jsonBytes)
    fmt.Println(jsonString)
}
500 chars
29 lines

In this example, we define a struct called Person with two fields: Name and Age. We create a Person object and then use json.Marshal() to encode it to JSON. Finally, we convert the JSON bytes to a string and print it to the console.

Output:

{"Name":"Alice","Age":30}
26 chars
2 lines

related categories

gistlibby LogSnag