Created
May 17, 2019 07:00
-
-
Save bonfy/6579a3e32cbd74ec4a9c475ceb0d6ed5 to your computer and use it in GitHub Desktop.
Merge List Name Value like Json
This file contains hidden or 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" | |
"fmt" | |
) | |
type Param struct { | |
Name string `json:"name"` | |
Value interface{} `json:"value"` | |
} | |
func List2Map(l []Param) map[string]interface{} { | |
result := make(map[string]interface{}) | |
for _,i := range l { | |
result[i.Name] = i.Value | |
} | |
return result | |
} | |
func Map2List(o map[string]interface{}) []Param { | |
var result []Param | |
for i := range o { | |
result = append(result, Param{Name: i, Value: o[i]}) | |
} | |
return result | |
} | |
func MergeMap(old, ne map[string]interface{}) map[string]interface{} { | |
result := make(map[string]interface{}) | |
for i := range old { | |
result[i] = old[i] | |
} | |
for i := range ne { | |
result[i] = ne[i] | |
} | |
return result | |
} | |
func MergeMapString(old, ne string) ([]Param, error) { | |
var oldParams []Param | |
err := json.Unmarshal([]byte(old), &oldParams) | |
if err!=nil { | |
return nil, err | |
} | |
//fmt.Println(oldParams) | |
var newParams []Param | |
err = json.Unmarshal([]byte(ne), &newParams) | |
if err!=nil { | |
return nil, err | |
} | |
//fmt.Println(newParams) | |
oldMap := List2Map(oldParams) | |
newMap := List2Map(newParams) | |
rstMap := MergeMap(oldMap, newMap) | |
rstList := Map2List(rstMap) | |
return rstList, nil | |
} | |
func main() { | |
//ne := `[{"name": "fullversion", "value": "01010101"}, {"name": "hello", "value": "world"}]` | |
//old := `[{"name": "fullversion", "value": ""}, {"name": "gitaddress", "value": "git://"}]` | |
ne := `[{"name": "fullversion", "value": "01010101"}, {"name": "hello", "value": 1}]` | |
old := `[{"name": "fullversion", "value": ""}, {"name": "gitaddress", "value": "git://"}, {"name": "hello", "value": 0}]` | |
rstList, err:= MergeMapString(old, ne) | |
if err!=nil { | |
fmt.Println("err") | |
} | |
fmt.Println(rstList) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment