如何将 Go 结构的一部分定义为 JSON 的字符串?

How do I define part of a Go struct as a string of JSON?

我有一个 JSON API 我正在尝试使用一个简单的 Go 应用程序,return 一个 JSON 字符串数组,将被插入存入数据库供以后使用。 JSON 模型如下所示:

 {
    "sites": {
        "count": 123,
        "site": [
            {
                "id": 111,
                "name": "abc"
            },
            {
                "id": 222,
                "name": "def"
            },
            {
                "id": 333,
                "name": "ghi"
            }
        ]
    }
}

所需的结果是一个如下所示的数组:

{"id": 111, "name": "abc"}
{"id": 222, "name": "def"}
{"id": 333, "name": "ghi"}

我似乎无法弄清楚的是如何定义一个在结构定义中的某个点停止解组的结构。有没有办法将 [] 结构的内容转储到结构数组中每个元素的字符串中,而不是定义子结构的内容?

您可以使用 json.RawMessage:

type Sites struct {
   Count int `json:"count"`
   SiteArr []json.RawMessage `json:"site"`
}

当您将数据解组到上述结构中时,SiteArr 的每个元素都将包含每个元素的原始 JSON 消息,您可以使用 [=13 从中获取字符串值=]