json.dumps如果重新排序字典鍵,我需要確保生成的字串永遠不會改變。
從測驗來看,傳遞sort_keys=True確實可以解決問題,并且它確實遞回地確保對欄位進行排序。
然而,官方檔案對遞回性質/行為并不明確和模棱兩可。
如果 sort_keys 為 true(默認值:False),則字典的輸出將按 key 排序;這對于回歸測驗很有用,以確保可以每天比較 JSON 序列化。
我應該撰寫自己的遞回函式來遞回轉儲密鑰還是依靠 python 來完成。
import json
a = {
"one": "one",
"nested": {
"two": "two",
"three": "three",
"nested": {
"four": "four",
"five": "five"
}
}
}
a_str = json.dumps(a, sort_keys=True)
print(a_str)
b = {
"nested": {
"three": "three",
"two": "two",
"nested": {
"five": "five",
"four": "four"
}
},
"one": "one"
}
b_str = json.dumps(b, sort_keys=True)
print(b_str)
print(a_str == b_str) # prints true
assert a_str == b_str
assert a_str != json.dumps(b) # Works as sort_keys is False by default
復制
uj5u.com熱心網友回復:
是的,您可以信賴這種行為。
事實上,你參考的他們的宣告:
這對于回歸測驗很有用,以確保可以每天比較 JSON 序列化
如果sort_keys不在嵌套的 JSON 物件上遞回作業,那將是錯誤的。
uj5u.com熱心網友回復:
如果您在某種意義上閱讀該檔案,則該檔案非常清楚
所有已編碼的字典都將對其鍵進行排序
從 JSON 編碼器的來源也可以看出這一點;_iterencode_dict為遇到的每個字典呼叫(即使從例如default=callable回傳)。
https://github.com/python/cpython/blob/8e75c6b49b7cb8515b917f01b32ece8c8ea2c0a0/Lib/json/encoder.py#L333-L355
def _iterencode_dict(dct, _current_indent_level):
# ...
if _sort_keys:
items = sorted(dct.items())
else:
items = dct.items()
# ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/403369.html
標籤:
