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.

GoData Integrity

Code

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

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:`.