Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Marshal From Escaping Quotes on String Field of Struct

Tags:

json

go

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.

like image 650
BlinkyTop Avatar asked Jul 21 '14 08:07

BlinkyTop


People also ask

How do I remove backslash from JSON string in Golang?

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 \ .

How do I decode JSON in Golang?

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.


1 Answers

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.

like image 54
Ainar-G Avatar answered Oct 12 '22 15:10

Ainar-G