dsgrs26202 2018-08-14 06:10
浏览 35
已采纳

是否可以在Go中按原样添加嵌套的json?

Is this possible way to add nested json "as is". The nested json doesn't have any structure and might be different. I need to put the nested json data directly to the root node.

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

type RootJson struct {
    NestedJson []byte
    AdditionalField string
}

func main() {
    nestedJson := []byte("{\"number\": 1, \"string\": \"string\", \"float\": 6.56}")

    rootJson := RootJson{nestedJson, "additionalField"}
    payload, _ := json.Marshal(&rootJson)

    fmt.Println(string(payload))

}
  • 写回答

1条回答 默认 最新

  • douyin2962 2018-08-14 06:13
    关注

    Yes, it's possible. Use the json.RawMessage type which implements custom marshaling / unmarshaling, which "renders" it as-is into the JSON output. It's just a plain byte slice:

    type RawMessage []byte
    

    Its value should be the UTF-8 encoded byte sequence of the raw JSON text (exactly what you get when you do a conversion, e.g. []byte("someText")).

    type RootJson struct {
        NestedJson      json.RawMessage
        AdditionalField string
    }
    

    With this, the output will be (try it on the Go Playground):

    {"NestedJson":{"number":1,"string":"string","float":6.56},
        "AdditionalField":"additionalField"}
    

    (Indentation added by me.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部