![](/img/trans.png)
[英]What's the most Pythonic way to parse out this value from a JSON-like blob?
[英]What's the most pythonic way to copy JSON fields to another JSON structure?
這里是上下文:
我有一個不能接受JSON結構的部分更新的數據庫。 要修改記錄,您必須讀取整個JSON記錄,進行修改,然后寫回JSON記錄,以覆蓋之前的JSON記錄。
我們收到最終用戶對這些JSON記錄的更新。 我們不會盲目地相信用戶正在提供有效且完整的新JSON記錄,因此我們檢查其更新是否僅包含我們允許的字段名稱。
因此,目標是說出類似以下內容:
1: receive inbound JSON from user along with record id
2: grab the existing JSON from the database for that record id
3: for each fieldname in (a list of permitted fieldnames)
4: if the fieldname is present in the inbound JSON
5: add that field or update its contents to the existing JSON record
6: write the resulting JSON structure back to the database
我的問題是,實現步驟3、4和5的最Pythonic方法是什么?
我知道Python在這類事情上非常擅長,而且我已經看到了一些非常優雅的代碼,可以完成類似的事情。
任何人都可以提出一種非常優雅和Pythonic的通用方法嗎?
請注意,我只對Python 3感興趣。
謝謝
existing = {"a": 1, "b": 2, "c": 3}
inbound = {"b": 3, "c": 4, "d": 5}
permitted = {"a","b","c"}
existing.update((key, val) for (key, val) in inbound.items() if key in permitted)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.