github.com/jdolitsky/cnab-go@v0.7.1-beta1/bundle/replacement/jsonreplacer.go (about) 1 package replacement 2 3 import ( 4 "encoding/json" 5 ) 6 7 // NewJSONReplacer creates a Replacer for JSON documents. 8 func NewJSONReplacer(indent string) Replacer { 9 return jsonReplacer{ 10 indent: indent, 11 } 12 } 13 14 type jsonReplacer struct { 15 indent string 16 } 17 18 func (r jsonReplacer) Replace(source string, selector string, value string) (string, error) { 19 dict := make(map[string]interface{}) 20 err := json.Unmarshal([]byte(source), &dict) 21 22 if err != nil { 23 return "", err 24 } 25 26 selectorPath := parseSelector(selector) 27 err = replaceIn(jsonDocMap(dict), selectorPath, value) 28 if err != nil { 29 return "", err 30 } 31 32 bytes, err := json.MarshalIndent(dict, "", r.indent) 33 if err != nil { 34 return "", err 35 } 36 return string(bytes), nil 37 } 38 39 type jsonDocMap map[string]interface{} 40 41 func (m jsonDocMap) get(key string) (interface{}, bool) { 42 e, ok := m[key] 43 return e, ok 44 } 45 46 func (m jsonDocMap) set(key string, value interface{}) { 47 m[key] = value 48 } 49 50 func (m jsonDocMap) asInstance(value interface{}) (docmap, bool) { 51 if e, ok := value.(map[string]interface{}); ok { 52 return jsonDocMap(e), ok 53 } 54 return jsonDocMap{}, false 55 }