Removing fields from struct or hiding them in JSON Response

后端 未结 13 1342
孤街浪徒
孤街浪徒 2020-12-12 09:37

I\'ve created an API in Go that, upon being called, performs a query, creates an instance of a struct, and then encodes that struct as JSON before sending back to the caller

13条回答
  •  有刺的猬
    2020-12-12 10:14

    I created this function to convert struct to JSON string by ignoring some fields. Hope it will help.

    func GetJSONString(obj interface{}, ignoreFields ...string) (string, error) {
        toJson, err := json.Marshal(obj)
        if err != nil {
            return "", err
        }
    
        if len(ignoreFields) == 0 {
            return string(toJson), nil
        }
    
        toMap := map[string]interface{}{}
        json.Unmarshal([]byte(string(toJson)), &toMap)
    
        for _, field := range ignoreFields {
            delete(toMap, field)
        }
    
        toJson, err = json.Marshal(toMap)
        if err != nil {
            return "", err
        }
        return string(toJson), nil
    }
    

    Example: https://play.golang.org/p/nmq7MFF47Gp

提交回复
热议问题