Golang json map(string)interface

func Unmarshal(data []byte, v interface{}) error

Requirement: convert json string to structure
1) Predefine the structure type corresponding to json;
2) Call json.Unmarshl

func main() {
     // Here, the backtick means not to change meaning, that is, the string type
     resp := `{"code":0,"message":"success","grades":[{"gradeClass":"First Grade","Score":{"chinese":99,"english":88 }},{"gradeClass":"Grade 2","Score":{"chinese":100,"english":98}}]}`
     var stu Student
     err := json. Unmarshal([]byte(resp), &stu)
     if err != nil {
     // 2021/08/12 23:37:19 {0 success [{first grade {99 88}} {second grade {100 98}}]}
type Student struct {
     Code int `json:"code"` // Use tag to indicate the field name corresponding to json
     Message string `json:"message"`
     Grades []GradeType `json:"grades"` // structure class array
type GradeType struct {
     GradeClass string `json:"gradeClass"`
     Score ScoreType
type ScoreType struct {
     Chinese int `json:"chinese"`
     English int `json:"english"`

The json string is deserialized into a map

// Forcibly convert interface type to string type (note: not convert.ToJSONString)
     wordCloudJson := convert.ToString(data[0]["word_cloud_json"])
     words := make(map[string]interface{})
     err = json. Unmarshal([]byte(wordCloudJson), &words)
     if err != nil {
         logu.CtxError(ctx, error_code.ProcessError, "GetBrandWordCloud Unmarshal", "wordCloudJson:%v, error: %v", wordCloudJson, err)
         return result, err
     for k, v := range words {
         result = append(result, &competition_detail. BrandWord{
             ProductPropertyValue: k,
             ProductFrequency: convert.ToInt64(v),
     // Take TOP 100 in descending order
     top(&result, 100)

Leave a Reply

Your email address will not be published. Required fields are marked *