Created
October 19, 2021 11:48
-
-
Save rytsh/05f14c9e7ec364a5a108806339b85b09 to your computer and use it in GitHub Desktop.
Embed Map to JSON output
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 ( | |
| "bytes" | |
| "encoding/json" | |
| "fmt" | |
| ) | |
| type test struct { | |
| KeyValue map[string]interface{} `json:"-"` | |
| Info string `json:"info"` | |
| } | |
| func (m test) MarshalJSON() ([]byte, error) { | |
| // using to disable recursive this function | |
| type newTestType test | |
| // marshal everything with json's original method | |
| preByte, err := json.Marshal(&struct { | |
| *newTestType | |
| }{ | |
| newTestType: (*newTestType)(&m), | |
| }) | |
| if err != nil { | |
| return nil, err | |
| } | |
| buffer := bytes.NewBuffer([]byte{}) | |
| // delete close bracket | |
| buffer.Write(preByte[:len(preByte)-1]) | |
| // add new values to buffer | |
| length := len(m.KeyValue) | |
| count := 0 | |
| if length > 0 { | |
| buffer.WriteString(",") | |
| } | |
| for key, value := range m.KeyValue { | |
| jsonValue, err := json.Marshal(value) | |
| if err != nil { | |
| return nil, err | |
| } | |
| buffer.WriteString(fmt.Sprintf("\"%s\":%s", key, string(jsonValue))) | |
| count++ | |
| if count < length { | |
| buffer.WriteString(",") | |
| } | |
| } | |
| buffer.WriteString("}") | |
| return buffer.Bytes(), nil | |
| } | |
| func main() { | |
| myStruct := test{ | |
| Info: "Testing Struct", | |
| } | |
| myStruct.KeyValue = make(map[string]interface{}) | |
| myStruct.KeyValue["language"] = "go" | |
| myStruct.KeyValue["year"] = 2007 | |
| // myStruct.KeyValue["info"] = "uuu" | |
| // print result | |
| rest, err := json.Marshal(myStruct) | |
| if err != nil { | |
| println(err) | |
| return | |
| } | |
| println(string(rest)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment