JSON Duplicate Keys Last Wins
Decode objects holding repeated keys into map and struct targets, showing how encoding/json resolves the collision deterministically.
Code
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
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.Duplicate Line RemoverFind unique, duplicate, or counted lines with optional case sensitivity and whitespace trimming, all processed locally in the browser.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 Duplicate Keys Last Wins print when run?
- Run it as a complete program — the output lines carry labels such as `map:`, `map value:`, `struct:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.