I'm reading a CSV file and parsing it to some predefined structure (struct in this case), I also need to store all the columns fields which will be different for every CSV file, and the goal is to get unified data structure merging predefined structure and dynamic fields from CSV file.
I have already written a util function that converts struct into map using json.Marshal
and json.Unmarshal
, once I convert struct into map I merge it with dynamic fields which is map[string]interface{}
.
// StructToMap ..
func StructToMap(v interface{}) (map[string]interface{}, error) {
var preRow map[string]interface{}
i, err := json.Marshal(&v)
if err != nil {
return nil, err
}
json.Unmarshal(i, &preRow)
return preRow, nil
}
// AddMap ..
func AddMap(a map[string]interface{}, b map[string]interface{}) map[string]interface{} {
for k, v := range b {
a[k] = v
}
return a
}
type PreProcessRow struct {
RawText string `json:"raw"`
SanitizedText string `json:"edited"`
}
preProcessRow := &PreProcessRow {
RawText: "this is an example text",
SanitizedText: "this is an example text",
}
dynamicContent := map[string]interface{"foo": 1, "bar": 2}
row, err := StructToMap(&preProcessRow)
if err != nil {
return err
}
AddMap(row, dynamicContent) // {"raw": "this is an example text", "edited": "this is an example text", "foo": 1, "bar": 2}
This way I am able to merge these two structures but I am looking for better approach (if any) where I don't have to json.Marshal
and json.Unmarshal