github.com/anchore/syft@v1.38.2/syft/pkg/key_value.go (about) 1 package pkg 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "sort" 7 ) 8 9 // KeyValue represents a single key-value pair. 10 type KeyValue struct { 11 // Key is the key name 12 Key string `json:"key"` 13 14 // Value is the value associated with the key 15 Value string `json:"value"` 16 } 17 18 // KeyValues represents an ordered collection of key-value pairs that preserves insertion order. 19 type KeyValues []KeyValue 20 21 func (k KeyValues) Get(key string) (string, bool) { 22 for _, kv := range k { 23 if kv.Key == key { 24 return kv.Value, true 25 } 26 } 27 28 return "", false 29 } 30 31 func (k KeyValues) MustGet(key string) string { 32 for _, kv := range k { 33 if kv.Key == key { 34 return kv.Value 35 } 36 } 37 38 return "" 39 } 40 41 func keyValuesFromMap(m map[string]string) KeyValues { 42 var result KeyValues 43 var mapKeys []string 44 for k := range m { 45 mapKeys = append(mapKeys, k) 46 } 47 sort.Strings(mapKeys) 48 for _, k := range mapKeys { 49 result = append(result, KeyValue{ 50 Key: k, 51 Value: m[k], 52 }) 53 } 54 return result 55 } 56 57 func (k *KeyValues) UnmarshalJSON(b []byte) error { 58 var kvs []KeyValue 59 if err := json.Unmarshal(b, &kvs); err != nil { 60 var legacyMap map[string]string 61 if err := json.Unmarshal(b, &legacyMap); err != nil { 62 return fmt.Errorf("unable to unmarshal KeyValues: %w", err) 63 } 64 var keys []string 65 for k := range legacyMap { 66 keys = append(keys, k) 67 } 68 sort.Strings(keys) 69 for _, k := range keys { 70 kvs = append(kvs, KeyValue{Key: k, Value: legacyMap[k]}) 71 } 72 } 73 *k = kvs 74 return nil 75 }