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

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. Then how do we convert from json.RawMessage back into a string? I looked at the methods available for RawMessage. Can't find anything that gives me back a string. Postgres json is nothing but a text data type with some additional semantics attached. So the contactinfo should become a string in the end.
You just cast the json.RawMessage to a string. See the updated Playground link in the answer.
Oh! Interesting. I didn't know one could simply cast it like in other languages. Long way to go (pun intended) still to fully understand go
For those still in the learn mode like me - the type conversion is actually written in the spec. See this - golang.org/ref/spec#Conversions
Yes. My initial comment stated that json.RawMessage should be cast to a string when it is in fact a type conversion ant not a cast.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.