Go

Parse JSON in Go (Golang)

Learn how to parse and encode JSON in Go using encoding/json package with Marshal, Unmarshal, and struct tags.

Try JSON Formatter →

Code Example

package main

import (
    "encoding/json"
    "fmt"
)

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

func main() {
    // Parse JSON to struct
    jsonStr := `{"name": "John", "age": 30}`
    var user User
    err := json.Unmarshal([]byte(jsonStr), &user)
    if err != nil {
        panic(err)
    }
    fmt.Println(user.Name) // John

    // Convert struct to JSON
    newUser := User{Name: "Jane", Age: 25}
    jsonBytes, _ := json.Marshal(newUser)
    fmt.Println(string(jsonBytes))

    // Pretty print
    prettyBytes, _ := json.MarshalIndent(newUser, "", "  ")
    fmt.Println(string(prettyBytes))

    // Parse to map (dynamic)
    var data map[string]interface{}
    json.Unmarshal([]byte(jsonStr), &data)
}
Key Points: Go uses struct tags to map JSON fields. json.Marshal/Unmarshal for conversion. Use map[string]interface{} for dynamic JSON.

Related Examples

More Go Examples