dongqi6486 2014-07-21 08:42
浏览 65
已采纳

防止元帅在结构的字符串字段中转义引号

I am having an issue parsing the following structure, where JsonData is a string of JSON stored in a database.

type User struct {
    Id          uint64  `json:"user_id"`
    JsonData    string  `json:"data"`
}

user := &User {
    Id: 444,
    JsonData: `{"field_a": 73, "field_b": "a string"}`,
}

If I json.Marshal this, it will escape the quotes but that will give me the JSON:

{
    "user_id" : 444,
    "data": "{\"field_a\": 73, \"field_b\": \"a string\"}"
}

Is there a way to tell the marshaller to avoid escaping the JsonData string and putting it in quotes, so it looks like this?

{
    "user_id" : 444,
    "data": {"field_a": 73, "field_b": "a string"}
}

I would prefer to not jump through too many hoops like creating an entirely new User-like object and/or unmarshaling/remarshaling the string etc.

  • 写回答

2条回答 默认 最新

  • drzrzzkh462254 2014-07-21 08:49
    关注

    Seems like RawMessage is what you are looking for:

    RawMessage is a raw encoded JSON object. It implements Marshaler and Unmarshaler and can be used to delay JSON decoding or precompute a JSON encoding.

    Playground: http://play.golang.org/p/MFNQlISy-o.

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

报告相同问题?