github.com/crossplane/upjet@v1.3.0/pkg/resource/json/canonical.go (about) 1 // SPDX-FileCopyrightText: 2024 The Crossplane Authors <https://crossplane.io> 2 // 3 // SPDX-License-Identifier: Apache-2.0 4 5 package json 6 7 import ( 8 jsoniter "github.com/json-iterator/go" 9 "github.com/pkg/errors" 10 ) 11 12 const ( 13 errFmtJSONUnmarshal = "failed to unmarshal the JSON document: %s" 14 errFmtJSONMarshal = "failed to marshal the dictionary: %v" 15 ) 16 17 var ( 18 cJSON = jsoniter.Config{ 19 SortMapKeys: true, 20 }.Froze() 21 ) 22 23 // Canonicalize minifies and orders the keys of the specified JSON document 24 // to return a canonical form of it, along with any errors encountered during 25 // the process. 26 func Canonicalize(json string) (string, error) { 27 var d any 28 if err := cJSON.Unmarshal([]byte(json), &d); err != nil { 29 return "", errors.Wrapf(err, errFmtJSONUnmarshal, json) 30 } 31 buff, err := cJSON.Marshal(d) 32 return string(buff), errors.Wrapf(err, errFmtJSONMarshal, d) 33 }