亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

格式化 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 關注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號