Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unmarshall json into database json field for postgres

Tags:

go

type A struct {
   Id int64
   ContactInfo sql.NullString `sql:"type:json"`
}

Given this json - {"Id": 1, "ContactInfo": {"email1": "[email protected]", "phone1": "2223334444"}}, how do we go about Unmarshaling the json into struct A. ContactInfo is just a simple json data type in postgres. I've looked around, but can't seem to find any easy way. Without any special handling, I simply get an error if I json.Unmarshal (error reads - json: cannot unmarshal object into Go value of type string).

What is desired is to leave ContactInfo untouched as a string so we can send it into postgres directly and postgres will verify if its valid json. However, Id should be unmarshaled and assigned as struct value.

like image 661
sat Avatar asked Mar 20 '23 13:03

sat


1 Answers

To parse JSON with embedded JSON you need to use a field of type json.RawMessage (and a second struct).

Check out this example for basic usage. You will then have access to the raw field contents for use in your database related structure.

like image 158
Michael Banzon Avatar answered Apr 01 '23 14:04

Michael Banzon