Prevention of Marshal's exit from quotes on the line field of the structure

I had a problem parsing the following structure, where JsonData is the JSON string stored in the 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 avoid quotes, but this will give me JSON:

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

Is there a way to tell the marshaller to avoid escaping JsonData and putting it in quotation marks so that it looks like this?

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

I would prefer not to skip too many hoops, how to create a completely new custom object and / or unwind / rearrange a string, etc.

+6
source share
2 answers

RawMessage seems to be 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 pre-compile JSON encoding.

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

+9
source

you can also use the 'string' tag in a field that tells the marshaller that the field is already in JSON:

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

Source: https://habr.com/ru/post/972569/


All Articles