JSON Struct Embedding Flattens Fields
Embed structs inside JSON payloads: anonymous fields without a tag flatten into the outer object, while an embedded type with a json tag stays a nested object.
Code
package main
import (
"encoding/json"
"fmt"
)
type Meta struct {
TraceID string `json:"trace_id"`
}
type Audit struct {
Actor string `json:"actor"`
}
type Envelope struct {
Meta // 匿名嵌入无 tag:字段被提升,编码时平铺进外层对象
Audit `json:"audit"` // 嵌入带 tag:保留为独立的嵌套子对象
Kind string `json:"kind"`
}
func main() {
in := []byte(`{"trace_id":"t-77","audit":{"actor":"svc-indexer"},"kind":"event"}`)
var env Envelope
if err := json.Unmarshal(in, &env); err != nil {
fmt.Println("decode:", err)
return
}
fmt.Println("promoted:", env.TraceID)
fmt.Println("nested:", env.Audit.Actor, "kind:", env.Kind)
out, err := json.Marshal(env)
if err != nil {
fmt.Println("encode:", err)
return
}
fmt.Println("round trip:", string(out))
}How the snippet works
JSON Struct Embedding Flattens Fields reduces to the function main.
Error handling is inline: 2 places test err != nil and branch immediately.
Applying it
Running the file prints labeled results such as decode:, promoted:, nested: — each operation’s effect is visible in the output.
Statements that carry the weight
if err != nil {
fmt.Println("encode:", err)
return
}
Interactive Tools for This Topic
JSON Repair & InspectorDeterministically repair malformed JSON with trailing commas, comments, single quotes, unquoted keys, and Python literals alongside a repair log.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.
FAQ
- What does JSON Struct Embedding Flattens Fields print when run?
- Run it as a complete program — the output lines carry labels such as `decode:`, `promoted:`, `nested:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.