Issues retrieving json from postgresql

hey everyone :slight_smile:
im making an api for funsies and ran into a problem when trying to get a test entry from the database. maybe I datafilled it wrong, or maybe im doing everything wrong…idk.

here is what im trying to retrieve:

type Config struct {
	ID        int       `json:"id"`
	Name      string    `json:"name"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	Plan      Plan      `json:"plan"`
}

type Plan struct {
	Name  string        `json:"name"`
	Steps []Instruction `json:"steps"`
}

the error I get from go is: Scan error on column index 3, name “plan”: pq: destination *data.Plan is not a pointer to array or slice

here is the query:

q := `select id, created_at, updated_at, plan from configurations`
	rows, err := db.QueryContext(ctx, q)
	if err != nil {
		return nil, err
	}

	defer rows.Close()
	var configs []*Config

	for rows.Next() {
		var cfg Config
		err := rows.Scan(
			&cfg.ID,
			&cfg.CreatedAt,
			&cfg.UpdatedAt,
			// &cfg.Plan,
			pq.Array(&cfg.Plan),
		)
		if err != nil {
			return nil, err
		}
		configs = append(configs, &cfg)
	}

here is the json i tried storing in the database as JSONB:

1 {                                                                                               
  2     "name": "jabber",                                                                           
  3     "steps": [{                                                                                 
  4         "id": 1,                                                                                
  5         "name": "first",                                                                        
  6         "hosts": ["fake1", "fake2"],                                                            
  7         "command": "putup",                                                                     
  8         "fatal": false,                                                                         
  9         "timeout": 62                                                                           
 10     }]                                                                                          
 11                                                                                                 
 12 }

thanks much!

Hi @rexlx,

The DB column plan appears to contain the JSON string you posted, correct? The code tries to scan this JSON string into a field of type Plan (a struct type).

What I would try is to scan the plan column into a string and then unmarshal that string into the Plan and Instructions structs (using encoding/json).

I think this will do the trick, I appreciate it @christophberger

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.