在 Go JSON 编组中嵌入 map[string]string 而无需额外 JSON 属性(内联)

Embed map[string]string in Go JSON marshaling without extra JSON property (inline)

有没有办法嵌入 map[string]string 内联?

我得到的是:

{
    "title": "hello world",
    "body": "this is a hello world post",
    "tags": {
        "hello": "world"
    }
}

我所说的嵌入或内联是这样的预期结果:

    {
    "title": "hello world",
    "body": "this is a hello world post",
    "hello": "world"
}

这是我的代码...我从 yaml 文件加载信息,并希望从上面以所需的格式 return JSON:

这是我的 yaml:

title: hello world
body: this is a hello world post
tags:
  hello: world

这是我的 Go 代码:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"

    "gopkg.in/yaml.v2"
)

type Post struct {
    Title string            `yaml:"title" json:"title"`
    Body  string            `yaml:"body" json:"body"`
    Tags  map[string]string `yaml:"tags" json:",inline"`
}

func main() {

    yamlBytes, err := ioutil.ReadFile("config.yaml")
    if err != nil {
        panic(err)
    }

    var post Post

    yaml.Unmarshal(yamlBytes, &post)

    jsonBytes, err := json.Marshal(post)
    if err != nil {
        panic(err)
    }

    fmt.Println(string(jsonBytes))

}

这显然有效:

Tags map[string]string `yaml:"tags" json:",inline"`

但我希望存在类似的东西来嵌入没有 JSON 属性 tags.

tags 地图

"flatten" 字段没有本地方法,但您可以通过一系列 Marshal/Unmarshal 步骤手动完成(为简洁起见省略了错误处理):

type Post struct {
    Title string            `yaml:"title" json:"title"`
    Body  string            `yaml:"body" json:"body"`
    Tags  map[string]string `yaml:"tags" json:"-"` // handled by Post.MarshalJSON
}

func (p Post) MarshalJSON() ([]byte, error) {
    // Turn p into a map
    type Post_ Post // prevent recursion
    b, _ := json.Marshal(Post_(p))

    var m map[string]json.RawMessage
    _ = json.Unmarshal(b, &m)

    // Add tags to the map, possibly overriding struct fields
    for k, v := range p.Tags {
        // if overriding struct fields is not acceptable:
        // if _, ok := m[k]; ok { continue }
        b, _ = json.Marshal(v)
        m[k] = b
    }

    return json.Marshal(m)
}

https://play.golang.org/p/Xvu2VYeZFGh