github.com/PDOK/gokoala@v0.50.6/internal/engine/util/json.go (about) 1 package util 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "log" 7 8 "dario.cat/mergo" 9 ) 10 11 func PrettyPrintJSON(content []byte, name string) []byte { 12 var pretty bytes.Buffer 13 if err := json.Indent(&pretty, content, "", " "); err != nil { 14 log.Print(string(content)) 15 log.Fatalf("invalid json in %s: %v, see json output above", name, err) 16 } 17 return pretty.Bytes() 18 } 19 20 // MergeJSON merges the two JSON byte slices. It returns an error if x1 or x2 cannot be JSON-unmarshalled, 21 // or the merged JSON is invalid. 22 // 23 // Optionally, an orderBy function can be provided to alter the key order in the resulting JSON 24 func MergeJSON(x1, x2 []byte, orderBy func(output map[string]any) any) ([]byte, error) { 25 var j1 map[string]any 26 err := json.Unmarshal(x1, &j1) 27 if err != nil { 28 return nil, err 29 } 30 var j2 map[string]any 31 err = json.Unmarshal(x2, &j2) 32 if err != nil { 33 return nil, err 34 } 35 err = mergo.Merge(&j1, &j2) 36 if err != nil { 37 return nil, err 38 } 39 if orderBy != nil { 40 return json.Marshal(orderBy(j1)) 41 } 42 return json.Marshal(j1) 43 }