Join GitHub today
GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.Sign up
encoding/json: unmarshal accepts duplicate keys #24415
Unmarshaling a JSON object with repeated keys into a struct doesn't return an error, it keeps the value specified last in the JSON string instead.
More confusingly, it causes maps on repeated keys to be merged: https://play.golang.org/p/47_7kSPFCW2
Other languages' JSON libraries error in this case
The documentation doesn't specify what happens in this case; it says it matches object keys to fields but doesn't specify in what order it does so (it only matters with duplicate keys). Changing the current behaviour might break backwards compatibility too much, but I think at least it should be documented.
Also, the behaviour is inconsistent between a map and a slice field; the maps get merged, the slice field takes the last value seen, like the other types.
@rsc thanks for the reply. You're right that the godoc says that keys are matched, so it is implicit that nothing is done about duplicate keys. However, I don't see how that should lead to maps getting merged.
That is, in @Dirbaio's second play link, I would expect the output to be
I understand that unmarshalling multiple times into one map merges the keys - that is fine. What I don't think is fine is for duplicate keys to get merged. For example, as @dpinela said, when the field is a slice they aren't merged and you get a single element: https://play.golang.org/p/nXLs0hd8Uj3