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.
A quick post on how to get an equivalent to PHP's stripslashes() function in Golang. Basically in PHP, the stripslashes() function will remove any backslashes from a string. \' becomes ' and double backslashes \\ are made into a single backslash \ .
To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct. Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. Note: If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With