Created
November 29, 2020 08:36
-
-
Save mittachaitu/86ac7717230d54a9ce6b45503cc6cd99 to your computer and use it in GitHub Desktop.
Get modified data from JSON documents
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
jsonpatch "github.com/evanphx/json-patch" | |
"github.com/pkg/errors" | |
// "k8s.io/apimachinery/pkg/util/strategicpatch" | |
) | |
// getPatchData will return difference between original and modified document | |
func getPatchData(originalObj, modifiedObj interface{}) ([]byte, error) { | |
originalData, err := json.Marshal(originalObj) | |
if err != nil { | |
return nil, errors.Wrapf(err, "failed marshal original data") | |
} | |
modifiedData, err := json.Marshal(modifiedObj) | |
if err != nil { | |
return nil, errors.Wrapf(err, "failed marshal original data") | |
} | |
// Using strategicpatch package can cause below error | |
// Error: CreateTwoWayMergePatch failed: unable to find api field in struct Unstructured for the json field "spec" | |
//patchBytes, err := strategicpatch.CreateTwoWayMergePatch(originalData, modifiedData, originalObj) | |
// if err != nil { | |
// return nil, errors.Errorf("CreateTwoWayMergePatch failed: %v", err) | |
// } | |
patchBytes, err := jsonpatch.CreateMergePatch(originalData, modifiedData) | |
if err != nil { | |
return nil, errors.Errorf("CreateTwoWayMergePatch failed: %v", err) | |
} | |
return patchBytes, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment