简体   繁体   English

将JSON字段复制到另一个JSON结构的最pythonic方法是什么?

[英]What's the most pythonic way to copy JSON fields to another JSON structure?

Here's the context: 这里是上下文:

  • I have a database that cannot accept partial updates of its JSON structures. 我有一个不能接受JSON结构的部分更新的数据库。 To modify a record you must read the whole JSON record, make modifications and then write back the JSON record, overwriting the previous JSON record. 要修改记录,您必须读取整个JSON记录,进行修改,然后写回JSON记录,以覆盖之前的JSON记录。

  • We receive updates from end users to these JSON records. 我们收到最终用户对这些JSON记录的更新。 We do not blindly trust that the user is providing a valid and complete new JSON record, so we check that their update contains only field-names that we permit. 我们不会盲目地相信用户正在提供有效且完整的新JSON记录,因此我们检查其更新是否仅包含我们允许的字段名称。

So, the objective is to say something like: 因此,目标是说出类似以下内容:

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

My question is, what is the most Pythonic way to implement steps 3, 4 and 5? 我的问题是,实现步骤3、4和5的最Pythonic方法是什么?

I know Python is extremely good at such things and I have seen some very elegant code that does similar things. 我知道Python在这类事情上非常擅长,而且我已经看到了一些非常优雅的代码,可以完成类似的事情。

Can anyone suggest a general approach that is very elegant and Pythonic? 任何人都可以提出一种非常优雅和Pythonic的通用方法吗?

Please note I'm only interested in Python 3. 请注意,我只对Python 3感兴趣。

thanks 谢谢

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM