Skip to content
This repository was archived by the owner on Jul 12, 2025. It is now read-only.
This repository was archived by the owner on Jul 12, 2025. It is now read-only.

Automatically Marshall JSON/JSONB/JSONBArray etc types as strings in Query Values #181

@jsnb-devoted

Description

@jsnb-devoted

I'm writing some code that selects all the data from a table and sends each row to a channel. Each row is going to eventually get put into a CSV so I need the types to eventually be strings. I've looked into defining a custom type and using RegisterDataType or QueryResultFormatsByOID but ultimately the JSON types seem to all return a byte array. Is there a quick way to override that so that the results from JSON fields are returned automatically as strings?

	sql := "SELECT * FROM my_table"
	var err error
	var values []interface{}

	rows, err := conn.Query(ctx, sql)
	if err != nil {
		return err
	}
	defer rows.Close()
	for rows.Next() {
		values, err = rows.Values()
		if err != nil {
			return err
		}

		r := RowType{
			TableName:   tableName,
			SchemaName:  schemaName,
		}
		for ix, v := range values {
			cr.Columns = append(cr.Columns, &r.Column{Value: v, Type: table.ColTypes[ix], Name: table.ColNames[ix]})
		}

		myChannel <- r

Feels like I could probably accomplish this by not using SELECT * and casting all my json type columns to strings in the query itself. I'm sure that is much fast but I'm hoping to understand a little better how to override the types in v4 (apologies if v5 totally changes the way this would be done). I had a similar issue with the uuid type until I ran into the https://github.com/jackc/pgx/wiki/UUID-Support doc

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions