doufocheng6233 2018-04-28 12:00
浏览 27
已采纳

结构化为JSON序列化

I am trying to create json serialized input data but not sure how to add the backslash () characters. Code below which can convert struct to json but not the way I require

Output: {"new":{"Id":"1","Class":"23"}} Expected: {\"new\":{\"Id\":\"1\",\"Class\":\"23\"}}

package main

import (
    "encoding/json"
    "fmt"
)

type Txn struct {
    Id    string `json:"Id"`
    Class string `json:"Class"`
}

type Send struct {
 New Txn `json:"new"`
}

func main() {
    fmt.Println("Creating serialized json")

    t := Txn{}
    t.Id = "1"
    t.Class = "23"

    fmt.Println(t)

    p := Send{}
    p.New = t

    fmt.Println("my p is", p)

    b, err := json.Marshal(p)
    if err != nil {
        fmt.Println("found some error ", err)
    }

    fmt.Println(string(b))
}
  • 写回答

1条回答 默认 最新

  • dongshengli6384 2018-04-28 13:06
    关注

    change last line to fmt.Printf("%q", string(b)) - this causes the format to be 'escaped string'.

    (or if you want to store the escaped string, ```fmt.Sprintf``)

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

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

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程