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.

GoData Integrity

Code

gosnippet
36 lines
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

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.