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

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

動態命名字段名稱

動態命名字段名稱

Go
慕斯王 2022-05-18 14:11:27
我想創建一個 JSON 響應,其中父對象的字段名稱具有動態名稱。最好用一個例子來解釋?,F在,我的回復是這樣的:{  "userId": 1,  "id": 1,  "title": "delectus aut autem",  "completed": false}為此,我創建了一個結構 -> 填充它 -> 返回它。我的結構如下所示:type Placeholder struct {    userId    int    `json:"userId"`    id        int    `json:"id"`    title     string `json:"title"`    completed bool   `json:"completed"`}//...res := Placeholder{  userId: 1,  id: 1,  title: "delectus aut autem",  completed: false,}現在我想使用 userId 作為字段名。所以我想要這個結果:{  "1": {     "id": 1,     "title": "delectus aut autem",     "completed": false  }}有沒有可能在 Go 中做到這一點?
查看完整描述

2 回答

?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

只需將resfrom的數據類型更改Placeholder為map[int]Placeholder。


userId := 1

res := map[int]Placeholder{

    userId: {

        id:        1,

        title:     "delectus aut autem",

        completed: false,

    },

}

fmt.Printf("%v", res)

游樂場: https: //play.golang.org/p/rCBl2r7fQTe


查看完整回答
反對 回復 2022-05-18
?
浮云間

TA貢獻1829條經驗 獲得超4個贊

您可以使用json:",inline".


注意:不要忽略實際代碼中的錯誤!


type Placeholder struct {

    ID        int    `json:"id"`

    Title     string `json:"title"`

    Completed bool   `json:"completed"`

}


type PlaceholderWithUserID struct {

    UserID      int `json:"userId"`

    Placeholder `json:",inline"`

}


type PlaceholderMap map[int]Placeholder


func main() {

    var res PlaceholderWithUserID

    _ = json.Unmarshal([]byte(`{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}`), &res)

    mapping := PlaceholderMap{

        res.UserID: res.Placeholder,

    }

    out, _ := json.Marshal(mapping)

    fmt.Println(string(out))

}


查看完整回答
反對 回復 2022-05-18
  • 2 回答
  • 0 關注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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