3

I am trying to convert a postgres column that is of type json to golang json object.

type MY_JSON struct {
  MY_ID string `json:"my_id"`
  MY_INFO []MY_INNER_JSON `json:"my_info"`
}

type MY_INNER_JSON struct {
    SOME_ID   string `json:"some_id"`
    SOME_NUM  int64 `json:"some_num"`
    SOME_OPTIONAL  string `json:"some_optional,omitempty"`
}

rows, err := db.Query("SELECT my_json FROM my_json_table LIMIT 1;")

for rows.Next() {
    var mycolumn MY_JSON
    err = rows.Scan(&mycolumn)
    fmt.Println(mycolumn)
}

This is what the json looks like

{
    "my_id": "this is my_id",
    "my_info": [
        {
            "some_id": "some_id",
            "some_num": 123
        },
        {
            "some_id": "some_id",
            "some_num": 123,
            "some_optional": "sometimes more"
        },
    ]
}

I am getting panic from golang during runtime.

Can someone point me a direction and tell me where I am doing wrong?

2
  • Have the MY_JSON type implement the sql.Scanner interface using json.Unmarshal. (make sure to implement the Scanner on a pointer type) Commented Jan 12, 2019 at 16:45
  • 2
    You would do well to rename your variables to be more Go idiomatic. Take a look at the naming suggestions in Effective Go. Commented Jan 12, 2019 at 16:50

1 Answer 1

3

By implementing the sql.Scanner interface on MY_JSON, your code should work as is. To do this, you need only to add the Scan method on the MY_JSON type (with pointer receiver).

func (m *MY_JSON) Scan(src interface{}) error {
    bs, ok := src.([]byte)
    if !ok {
        return errors.New("not a []byte")
    }
    return json.Unmarshal(bs, m)
}
Sign up to request clarification or add additional context in comments.

Comments

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.