Struct To Map Via JSON Roundtrip
Marshal a struct and unmarshal it into map[string]any to add or delete keys dynamically, then remarshal with keys in sorted order.
Code
package main
import (
"encoding/json"
"fmt"
)
type Order struct {
ID string `json:"id"`
Total float64 `json:"total"`
Status string `json:"status"`
}
func main() {
order := Order{ID: "o-1042", Total: 49.5, Status: "paid"}
// 结构体 → JSON → map[string]any:得到可动态增删键的视图 (roundtrip)
raw, err := json.Marshal(order)
if err != nil {
panic(err)
}
var view map[string]any
if err := json.Unmarshal(raw, &view); err != nil {
panic(err)
}
// 动态补一个结构体里没有的字段,再删掉一个已有字段
view["channel"] = "web"
delete(view, "status")
edited, err := json.Marshal(view)
if err != nil {
panic(err)
}
fmt.Println(string(edited))
}What the code does
The working parts are the function main.
Failure handling is panic(err): 3 checkpoints abort the program at the point a problem is detected.
Points of care
- Nothing to install: every API here comes with the runtime itself.
panic(err)is the only failure path here: the first problem stops the program.
Applying it
The signature doing the main work is func main()
Statements that decide the outcome
if err != nil {
panic(err)
}
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- How are errors reported?
- By aborting: each of the 3 `err != nil` branches calls `panic(err)`, so a failure stops the program at the point it is detected.
- How do you run Struct To Map Via JSON Roundtrip?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.