簡體   English   中英

如何使用特定字段作為鍵將結構轉換為 map?

[英]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 個步驟完成此操作:

  1. 使用omitempty使Id字段可選
  2. 使用make()定義並分配map[string]news類型的 map
  3. 迭代您的數據以填充map

更新結構

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"`
}

創建 Map

result := make(map[string]news)

填充 Map

// 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM