美文网首页
go json-patch CreateMergePatch

go json-patch CreateMergePatch

作者: allenhaozi | 来源:发表于2020-12-27 21:32 被阅读0次

CreateMergePatch

// CreateMergePatch will return a merge patch document capable of converting
// the original document(s) to the modified document(s).
// The parameters can be bytes of either two JSON Documents, or two arrays of
// JSON documents.
// The merge patch returned follows the specification defined at http://tools.ietf.org/html/draft-ietf-appsawg-json-merge-patch-07
func CreateMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) {
    originalResemblesArray := resemblesJSONArray(originalJSON)
    modifiedResemblesArray := resemblesJSONArray(modifiedJSON)

    // Do both byte-slices seem like JSON arrays?
    if originalResemblesArray && modifiedResemblesArray {
        return createArrayMergePatch(originalJSON, modifiedJSON)
    }

    // Are both byte-slices are not arrays? Then they are likely JSON objects...
    if !originalResemblesArray && !modifiedResemblesArray {
        return createObjectMergePatch(originalJSON, modifiedJSON)
    }

    // None of the above? Then return an error because of mismatched types.
    return nil, errBadMergeTypes
}

这是一个可以merge两个json的函数

比如

original JSON document

{
       "title": "Goodbye!",
       "author" : {
         "givenName" : "John",
         "familyName" : "Doe"
       },
       "tags":[ "example", "sample" ],
       "content": "This will be unchanged"
     }

send a patch request

PATCH /my/resource HTTP/1.1
Host: example.org
Content-Type: application/merge-patch+json

{
       "title": "Hello!",
       "phoneNumber": "+01-123-456-7890",
       "author": {
         "familyName": null
       },
       "tags": [ "example" ]
     }

result

{
       "title": "Hello!",
       "author" : {
         "givenName" : "John"
       },
       "tags": [ "example" ],
       "content": "This will be unchanged",
       "phoneNumber": "+01-123-456-7890"
     }

相关文章

网友评论

      本文标题:go json-patch CreateMergePatch

      本文链接:https://www.haomeiwen.com/subject/nbranktx.html