在Go JSON封送中嵌入map[string]字符串,无需额外的JSON属性(内联)

在Go JSON封送中嵌入map[string]字符串,无需额外的JSON属性(内联),json,go,marshalling,Json,Go,Marshalling,有没有办法嵌入map[string]stringinline 我得到的是: { "title": "hello world", "body": "this is a hello world post", "tags": { "hello": "world" } } 我对嵌入或内联的意思是预期结果如下: { "title": "hello world", "body": "this is a hello world post

有没有办法嵌入
map[string]string
inline

我得到的是:

{
    "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文件加载信息,希望从上面以所需格式返回JSON:

这是我的yaml:

title: hello world
body: this is a hello world post
tags:
  hello: world
这是我的密码:

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属性
标记

没有“展平”字段的本机方法,但您可以通过一系列封送/解封步骤手动执行(为简洁起见,省略了错误处理):


您希望如何处理冲突(例如,名为“title”的标记)?性能是一个问题吗?性能不是一个问题。这只是一个小问题。dublicate键可以被重写相关/类似:请小心删除struct标记中“json:”和“body”之间的空格,因为现在它被忽略,并且输出json包含大写的“body”键。@SirDarius是的,但它实际上是从问题中复制的,并且在问题中已经弄错了。@icza确实,但至少让我们确保答案完全正确:)谢谢!,我还固定了问题中json:“Body”周围的间距
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)
}