简体   繁体   English

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

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

I have a JSON API I'm attempting to consume with a simple Go application, and return an array of JSON strings, which will be inserted into a database for later consumption.我有一个 JSON API,我试图用一个简单的 Go 应用程序使用它,并返回一个 JSON 字符串数组,该数组将插入到数据库中以供以后使用。 The JSON model looks like this: JSON 模型如下所示:

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

The desired result is an array that looks like:所需的结果是一个如下所示的数组:

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

What I can't seem to figure out is how to define a struct that stops unmarshalling at a certain point in the struct definition.我似乎无法弄清楚如何定义一个在结构定义中的某个点停止解组的结构。 Is there a way to just dump the contents of the []struct into a string for each element in the struct array, instead of defining the contents of the sub-struct?有没有办法将 []struct 的内容转储到 struct 数组中的每个元素的字符串中,而不是定义子结构的内容?

You can use json.RawMessage :您可以使用json.RawMessage

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

When you unmarshal the data into the above struct, each element of SiteArr will contain the raw JSON message for each element, and you can get the string value from that using string(sites.SiteArr[i])当您将数据解组到上述结构中时, SiteArr每个元素将包含每个元素的原始 JSON 消息,您可以使用string(sites.SiteArr[i])从中获取字符串值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM