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.
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.
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"`
}