github.com/acoshift/pgsql@v0.15.3/json.go (about)

     1  package pgsql
     2  
     3  import (
     4  	"database/sql"
     5  	"database/sql/driver"
     6  	"encoding/json"
     7  	"fmt"
     8  )
     9  
    10  // JSON wraps value with scanner and valuer
    11  func JSON(value any) interface {
    12  	driver.Valuer
    13  	sql.Scanner
    14  } {
    15  	return &jsonValue{value}
    16  }
    17  
    18  type jsonValue struct {
    19  	value any
    20  }
    21  
    22  func (v *jsonValue) Scan(src any) error {
    23  	if src == nil {
    24  		return nil
    25  	}
    26  
    27  	var b []byte
    28  	switch p := src.(type) {
    29  	case []byte:
    30  		b = p
    31  	case string:
    32  		b = []byte(p)
    33  	default:
    34  		return fmt.Errorf("pgsql: JSON not support scan source")
    35  	}
    36  	return json.Unmarshal(b, v.value)
    37  }
    38  
    39  func (v jsonValue) Value() (driver.Value, error) {
    40  	return json.Marshal(v.value)
    41  }