JSON Duplicate Keys Last Wins

Decode objects holding repeated keys into map and struct targets, showing how encoding/json resolves the collision deterministically.

GoData Integrity

Code

gosnippet
41 lines
package main

import (
	"encoding/json"
	"fmt"
)

type Retry struct {
	Attempts int
	Backoff  string
}

func main() {
	// 同名键重复出现:encoding/json 取最后一个值
	payload := []byte("{"attempts":1,"attempts":3}")

	var m map[string]int
	if err := json.Unmarshal(payload, &m); err != nil {
		fmt.Println("map:", err)
		return
	}
	fmt.Println("map value:", m["attempts"])

	var r Retry
	if err := json.Unmarshal(payload, &r); err != nil {
		fmt.Println("struct:", err)
		return
	}
	fmt.Printf("struct: %+v\n", r)

	// 嵌套对象同样规则:每层独立按最后出现者为准
	nested := []byte("{"retry":{"backoff":"1s"},"retry":{"backoff":"5s"}}")
	var doc struct {
		Retry Retry
	}
	if err := json.Unmarshal(nested, &doc); err != nil {
		fmt.Println("nested:", err)
		return
	}
	fmt.Printf("nested backoff: %s\n", doc.Retry.Backoff)
}

How it works

JSON Duplicate Keys Last Wins comes down to the function main.

Error handling is inline: 3 places test err != nil and branch immediately.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Using it

Signature: func main()

Running the file prints labeled results such as map:, map value:, struct: — each operation’s effect is visible in the output.

Key statements

nested := []byte("{"retry":{"backoff":"1s"},"retry":{"backoff":"5s"}}")

Interactive Tools for This Topic

FAQ

What does JSON Duplicate Keys Last Wins print when run?
Run it as a complete program — the output lines carry labels such as `map:`, `map value:`, `struct:`.