防止Marshal在结构体的字符串字段上转义引号

huangapple go评论83阅读模式
英文:

Prevent Marshal From Escaping Quotes on String Field of Struct

问题

我遇到了解析以下结构的问题,其中JsonData是存储在数据库中的JSON字符串。

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

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

如果我对其进行json.Marshal,它会转义引号,但这将给我以下JSON:

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

有没有办法告诉编组器避免转义JsonData字符串并将其放在引号中,使其看起来像这样?

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

我希望不要通过太多的步骤来实现,比如创建一个全新的类似User的对象和/或对字符串进行解组/重新组合等。

英文:

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.

答案1

得分: 18

似乎你正在寻找的是RawMessage

RawMessage 是一个原始编码的 JSON 对象。它实现了 Marshaler 和 Unmarshaler 接口,可以用于延迟 JSON 解码或预先计算 JSON 编码。

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

英文:

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.

答案2

得分: 0

你还可以在字段上使用'string'标签,这将告诉编组器该字段已经是JSON格式的:

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

you can also use the 'string' tag on the field, which will tell the marshaller that the field is already in JSON:

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

huangapple
  • 本文由 发表于 2014年7月21日 16:42:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/24860888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定