为了账号安全,请及时绑定邮箱和手机立即绑定

格式化 json 数据或生成动态结构

格式化 json 数据或生成动态结构

Go
忽然笑 2022-12-19 11:55:10
{  "type": "object",  "properties": {    "firstName": {      "type": "string",      "title": "First name",      "default": "Chuck"    },    "lastName": {      "type": "string",      "title": "Last name"    },    "telephone": {      "type": "string",      "title": "Telephone",      "minLength": 10    }  }}我想构造上图所示的数据,并发送到前端进行渲染。它必须包含类型和属性字段。属性中的字段是核心数据。    //testMap is a map. key is variable name , value is value    testMap := DrawValueNameFromPareSelfFile(testPath)    marshal, _ := json.MarshalIndent(testMap, "", " ")    res := string(marshal)    helper.Ok(c, res)type Resp struct {    Code    errcode.Code `json:"code" binding:"required"`    Message string       `json:"message" binding:"required"`    Data    interface{}  `json:"data" binding:"required"`}// Okfunc Ok(c *gin.Context, data interface{}) {    c.JSON(http.StatusOK, Resp{        Code: errcode.ErrNone,        Data: data,    })}
查看完整描述

1 回答

?
蝴蝶刀刀

TA贡献1801条经验 获得超8个赞

您需要使用map动态字段。


真正的动态数据可以存储在map[string]interface{}


对于有限数量的字段,可以使用强类型:


type Response struct {

    Type       string              `json:"type"`

    Properties map[string]RespProp `json:"properties"`

}


type RespProp struct {

    Type      string `json:"type"`

    Title     string `json:"title"`

    Default   string `json:"default,omitempty"`

    MinLength int    `json:"minLength,omitempty"`

}

https://go.dev/play/p/W8mpg7HvCwM


查看完整回答
反对 回复 2022-12-19
  • 1 回答
  • 0 关注
  • 154 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号