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 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误