DevToolsForYou

JSON Formatter, Minifier, and Validator in Go — Code Examples

JSON Formatter, Minifier, and Validator in GoUse the online tool →

JSON parsing and serialisation is built into every major language. Here is how to parse a JSON string, format (pretty-print) JSON, and handle common edge cases in each language.

Go's encoding/json package uses struct tags for mapping. json.Marshal() serializes and json.Unmarshal() parses.

Go
package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
    Email string `json:"email,omitempty"` // omit if empty
}

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

    // Serialize struct → JSON
    out, err := json.Marshal(user)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(out)) // {"name":"Alice","age":30}

    // Pretty-print
    pretty, _ := json.MarshalIndent(user, "", "  ")
    fmt.Println(string(pretty))

    // Parse into map (for unknown structure)
    var m map[string]any
    json.Unmarshal(data, &m)
    fmt.Println(m["name"]) // Alice
}
Notes & gotchas
  • json.Unmarshal() requires a pointer — pass &variable, not variable.
  • Use omitempty in struct tags to skip zero-value fields in output.
  • json.Decoder is more efficient than json.Unmarshal when reading from an io.Reader (HTTP body, file).
Try it in your browser

Need to json formatter without writing code? The JSON Formatter, Minifier, and Validator runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open JSON Formatter
JSON Formatter, Minifier, and Validator in other languages