Decode as JSON and store the JSON as blob in DB

130 views
Skip to first unread message

mail...@gmail.com

unread,
Nov 16, 2017, 12:24:36 PM11/16/17
to golang-nuts
Hello,

     I am new to Go. I have structure like this for my REST POST request:

type Service struct {
ID       string `json:"id,omitempty" db:"id"`
Name     string `json:"name" db:"name"`
Contract struct {
Ha          string `json:"ha"`
ServiceTime int    `json:"service_time"`
Region      string `json:"region"`
} `json:"contract" db:"contract"`
}

If I change Contract type to String, the contract will be pushed as empty string in DB. I am storing Contract as blob type. What should I do to get the request as json and store in DB as blob ? 

Thanks

Tamás Gulácsi

unread,
Nov 16, 2017, 1:17:03 PM11/16/17
to golang-nuts
json.RawMessage

mail...@gmail.com

unread,
Nov 17, 2017, 2:31:19 AM11/17/17
to golang-nuts
Tamas,

    Can u explain ?

On Thursday, November 16, 2017 at 11:47:03 PM UTC+5:30, Tamás Gulácsi wrote:
json.RawMessage

Nathan Kerr

unread,
Nov 21, 2017, 9:36:44 AM11/21/17
to golang-nuts
I think what was meant was to define Service as:

type Service struct {
ID       string `json:"id,omitempty" db:"id"`
Name     string `json:"name" db:"name"`
Contract json.RawMessage `json:"contract" db:"contract"`
}

This assumes you don't need to access the contents of Service.Contract and they are meant to be stored in the db as a JSON-encoded blob (and that the db driver recognises json.RawMessage as something to store in a blob).

If one or more of these assumptions is not true, you will need separate structs for dealing with JSON and the db. For example:

type ServiceJSON struct {
ID       string `json:"id,omitempty"`
Name     string `json:"name"`
Contract struct {
Ha          string `json:"ha"`
ServiceTime int    `json:"service_time"`
Region      string `json:"region"`
} `json:"contract"`
}

and

type ServiceDB struct {
ID       string `db:"id"`
Name     string `db:"name"`
Contract []byte `db:"contract"`
}

and convert between them as needed.

Hope this helps,
Nathan
Reply all
Reply to author
Forward
0 new messages