【问题标题】:Apply json patch to a Mongoengine document将 json 补丁应用到 Mongoengine 文档
【发布时间】:2018-11-23 10:20:32
【问题描述】:

我正在尝试将 json-patch 应用到 Mongoengine 文档。

我正在使用这些 json-patch 库:https://github.com/stefankoegl/python-json-patch 和 mongoengine 0.14.3 和 python 3.6.3

这是我的实际代码:

json_patch = JsonPatch.from_string(jp_string)
document = Document.objects(id=document_id)
json_documents = json.loads(document.as_pymongo().to_json())
json_patched_document = json_patch.apply(json_documents[0])
Document.objects(id=document_id).first().delete()
Document
    .from_json(json.dumps(json_patched_document))
    .save(force_insert=True)

有没有更好的方法来保存已编辑的 json 文档?

我对代码做了一点改进:

json_patch = JsonPatch.from_string(jp_string)
document = Document.objects(id=document_id)
json_document = json.loads(document.as_pymongo().to_json())
json_patched_document = json_patch.apply(json_documents[0])
Document
    .from_json(json.dumps(json_patched_document), created=True)
    .save()

但是,有没有办法不将文档转换为 json?

【问题讨论】:

    标签: python json mongodb mongoengine json-patch


    【解决方案1】:

    我有一点类似的问题,我不想保存完整文档的部分,我只想更新修改/添加的字段。

    这是我在以下输入上测试的代码:

    def tryjsonpatch():
        doc_in_db = {'foo': 'bar', "name": "aj", 'numbers': [1, 3, 7, 8]}
        input = {'foo': 'bar', "name": "dj", 'numbers': [1, 3, 4, 8]}
        input2 = {'foo': 'bar', "name": "aj", 'numbers': [1, 3, 7, 8], "extera": "12"}
        input3 = {'foo': 'bar', "name": "dj", 'numbers': [1, 3, 4, 8], "extera": "12"}
    
        patch = jsonpatch.JsonPatch.from_diff(doc_in_db, input3)
        print("\n***patch***\n", patch)
        doc = get_minimal_doc(doc_in_db, patch)
    
        result = patch.apply(doc, in_place=True)
        print("\n###result###\n", result,
               "\n###present###\n", doc_in_db)
    
    
    def get_minimal_doc(present, patch):
        cur_dc = {}
        for change in patch.patch:
            if change['op'] not in ("add"):
                keys = change['path'].split("/")[1:]
                present_move = {}
    
                old_key = 1
                first = True
                for key in keys:
                    if key.isdigit():  # old_key represented a array
                        cur_dc[old_key] = present_move
                    else:
                        if first:
                            cur_dc[key] = {}
                            first = False
                        else:
                            cur_dc[old_key][key] = {}
    
                        old_key = key
                        present_move = present[old_key]
        return cur_dc
    tryjsonpatch()
    

    【讨论】:

      猜你喜欢
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      • 2014-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多