-
-
Save sh0umik/8e11b98ca5287ac8a6e0a0b35f3ea74a to your computer and use it in GitHub Desktop.
This file contains 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" | |
"github.com/fatih/structs" | |
"reflect" | |
"strings" | |
) | |
type Nested struct{ | |
Names []string | |
} | |
type JsonData struct { | |
RID string `json:"r_id,omitempty"` | |
Title string `json:"title,omitempty"` | |
Address struct { | |
City struct { | |
ID string `json:"id,omitempty"` | |
Name string `json:"name,omitempty"` | |
} `json:"city,omitempty"` | |
Postal string `json:"postal,omitempty"` | |
} `json:"address"` | |
Description string `json:"description,omitempty"` | |
} | |
func main() { | |
file := []byte(`{ | |
"r_id" : "123456", | |
"title" : "brand new restarant with changed name", | |
"address": { | |
"city": { | |
"id": "25", | |
"name": "Dhaka" | |
}, | |
"postal":"1213" | |
}, | |
"description" : "here are some new desciption " | |
}`) | |
var res JsonData | |
err := json.Unmarshal(file, &res) | |
if err != nil { | |
fmt.Printf("err : %s", err.Error()) | |
} | |
field := structs.Fields(res) | |
patch := make(map[string]interface{}) | |
result := mapFields(field, patch, &Nested{}) | |
fmt.Printf("%v", result) | |
// prints : map[address.city.id:25 address.city.name:Modhubag r_id:123456 title:brand new restarant with changed name] | |
// But not all string field like description and state of address | |
} | |
func mapFields(field []*structs.Field, patch map[string]interface{}, names *Nested) map[string]interface{} { | |
for _, k := range field { | |
if !k.IsZero() { | |
rf := reflect.TypeOf(k.Value()) | |
switch rf.Kind() { | |
case reflect.String: | |
fname := strings.Split(k.Tag("json"), ",") // to remove omitempty and get only the json field name | |
if len(names.Names) > 0 { | |
join := strings.Join(names.Names, ".") | |
patch[join+"."+fname[0]] = k.Value() | |
}else { | |
patch[fname[0]] = k.Value() | |
} | |
case reflect.Ptr: | |
fname := strings.Split(k.Tag("json"), ",") | |
names.Names = append(names.Names, fname[0]) | |
return mapFields(k.Fields(), patch, names) | |
} | |
} | |
} | |
return patch | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment