dsgrs26202 2018-08-14 14: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 14: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.)

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?