doudou3213 2019-06-19 18:31
浏览 125
已采纳

运行JSON Encode时是否可以排除已经为JSON的字段?

I am constructing a reply on a restAPI and using json.NewEncoder.Encode() to generate the JSON reply ( note : w is responsewriter).

u := Reply{Id: id, Status: "progress", Message: ""}
json.NewEncoder(w).Encode(u)

This works fine.

But I then have the other situation where Message will be populated with a string that is already in JSON format:

RetMessage := "{"debug": "on", "window": { "width": 500, "height": 500}}"
u := Reply{Id: id, Status: "progress", Message: RetMessage}
json.NewEncoder(w).Encode(u)

Then the reply will be the JSON with escaped quotations etc, which makes sense of course as it parses it as strings to JSON, but it of course breaks the concept as I would like the RetMessage to be passed on as it is, where the others I would like to be encoded to JSON.

Is there any way I can get around this in a smart way? The content in RetMessage is coming from a file so I can't change that the RetMessage sometimes do come as JSON encoded already.

  • 写回答

2条回答 默认 最新

  • duanchen7036 2019-06-19 19:17
    关注

    If Message is a complete, valid, JSON object, you can accomplish what you want by converting it to type json.RawMessage:

    type ReplyWithJSON struct {
        Id      int
        Status  string
        Message json.RawMessage
    }
    
    u := ReplyWithJSON{Id: id, Status: "progress", Message: json.RawMessage(RetMessage)}
    json.NewEncoder(w).Encode(u)
    

    This should generate the following output:

    {"Id":123,"Status":"progress","Message":{"debug":"on","window":{"width":500,"height":500}}}

    See it in action on the playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥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,如何解決?
  • ¥15 c++头文件不能识别CDialog