![](/img/trans.png)
[英]How to convert map column to struct type with custom key-value names?
[英]how to convert a struct to a map using a specific field as key?
我正在嘗試轉換此結構
type news struct {
Id string `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
Date string `json:"date"`
Escraped string `json:"escraped"`
Page string `json:"page"`
Body string `json:"body"`
Url string `json:"url"`
}
對於 Id 是關鍵的 map,今天當我對這個結構進行編碼時,我有以下 json 我在 function 中返回
[
{
"id": "someId",
"title": "something",
"author": "something",
"date": "something",
"escraped": "something",
"page": "https://something",
"body": "something",
"url": "https://something"
}
]
但是現在我想更改它並使用 id 作為鍵,所以我想返回
[
{
"someId": {
"title": "something",
"author": "something",
"date": "something",
"escraped": "something",
"page": "https://something",
"body": "something",
"url": "https://something"
}
}
]
我不太確定如何更改它以開始使用 ID 作為鍵而不是常規字段,我嘗試創建另一個 map 但我失敗了。
package main
import "fmt"
import "encoding/json"
type news struct {
Id string `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
Date string `json:"date"`
Escraped string `json:"escraped"`
Page string `json:"page"`
Body string `json:"body"`
Url string `json:"url"`
}
func main() {
m := &news{Id: "222"}
result := convert(m)
str, _ := json.Marshal(result)
fmt.Println(string(str))
}
func convert(m *news) interface{} {
type tmp struct {
*news
Id string `json:"id,omitempty"`
}
t := &tmp{news: m}
return map[string]interface{}{m.Id: t}
}
我在這里做一些假設:
news
結構,並且字段必須保持原樣[]news
片段中讀取的您可以通過 3 個步驟完成此操作:
omitempty
使Id
字段可選make()
定義並分配map[string]news
類型的 mapmap
type news struct {
Id string `json:"id,omitempty"`
Title string `json:"title"`
Author string `json:"author"`
Date string `json:"date"`
Escraped string `json:"escraped"`
Page string `json:"page"`
Body string `json:"body"`
Url string `json:"url"`
}
result := make(map[string]news)
// Transform a slice of news (called data) to a map (called result)
for _, entry := range data {
result[entry.Id] = news{
Title: entry.Title,
Author: entry.Author,
Date: entry.Date,
Escraped: entry.Escraped,
Page: entry.Page,
Body: entry.Body,
Url: entry.Url,
}
}
// Encode the map
encoded, _ := json.Marshal(result)
Output:
{"someId":{"title":"something","author":"something","date":"something","escraped":"something","page":"https://something","body":"something","url":"https://something"}}
請參閱此處的示例: https://play.golang.org/p/8z6M8HqCVgv
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.