...

Source file src/github.com/jackc/pgx/v4/example_json_test.go

Documentation: github.com/jackc/pgx/v4

     1  package pgx_test
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  
     8  	"github.com/jackc/pgx/v4"
     9  )
    10  
    11  func Example_JSON() {
    12  	conn, err := pgx.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE"))
    13  	if err != nil {
    14  		fmt.Printf("Unable to establish connection: %v", err)
    15  		return
    16  	}
    17  
    18  	type person struct {
    19  		Name string `json:"name"`
    20  		Age  int    `json:"age"`
    21  	}
    22  
    23  	input := person{
    24  		Name: "John",
    25  		Age:  42,
    26  	}
    27  
    28  	var output person
    29  
    30  	err = conn.QueryRow(context.Background(), "select $1::json", input).Scan(&output)
    31  	if err != nil {
    32  		fmt.Println(err)
    33  		return
    34  	}
    35  
    36  	fmt.Println(output.Name, output.Age)
    37  	// Output:
    38  	// John 42
    39  }
    40  

View as plain text