search
HomeBackend DevelopmentGolangConvert AWS redshiftdataapiservice.GetStatementResultOutput to JSON or structure

将 AWS redshiftdataapiservice.GetStatementResultOutput 转换为 JSON 或结构

Question content

I have an AWS Redshift Serverless database that I am querying through the redshiftdataapiservice of the AWS Go SDK. The query and all that works, but the records are returned in a format that is difficult to use/understand.

My code is like this:

import (
    "fmt"
    "log"
    "time"
    "os"
    "context"

    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/redshiftdata"
    "github.com/aws/aws-sdk-go-v2/service/redshiftdata/types"
)

// Execute a Redshift query and return a result statement output
func executeRedshiftQuery(sql string) (*redshiftdata.GetStatementResultOutput, error) {
    // Load the Shared AWS Configuration (~/.aws/config)
    cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(os.Getenv("AWS_REGION")))
    if err != nil {
        return nil, err
    }

    // Create a service client
    redshiftclient := redshiftdata.NewFromConfig(cfg)
    execStmt, err := redshiftclient.ExecuteStatement(context.TODO(), &redshiftdata.ExecuteStatementInput{
        WorkgroupName: aws.String(os.Getenv("WG_NAME")),
        Database:      aws.String(os.Getenv("DB_NAME")),
        Sql:           aws.String(sql),
    })
    if err != nil {
        return nil, err
    }

    // wait for query to finish
    for {
        descStmt, err := redshiftclient.DescribeStatement(context.TODO(), &redshiftdata.DescribeStatementInput{
            Id: execStmt.Id,
        })
        if err != nil {
            return nil, err
        }

        // return an error if the query failed or aborted
        if descStmt.Status == types.StatusStringFailed || descStmt.Status == types.StatusStringAborted {
            err := errors.New("the Redshift query failed or was aborted")
            return nil, err
        } else if descStmt.Status != types.StatusStringFinished {
            time.Sleep(1 * time.Second)
            continue
        }

        break
    }

    // get the results
    resultStmt, err := redshiftclient.GetStatementResult(context.TODO(), &redshiftdata.GetStatementResultInput{
        Id: execStmt.Id,
    })
    if err != nil {
        return nil, err
    }

    return resultStmt, nil
}

I find that 2D arrays of *Fields are difficult to work with. How do I (preferably simply) map this to a usable JSON, or rather an array of type structs? Or is there a way to request JSON from Redshift? If possible, I'd like to keep all of this entirely within my Golang application.


Correct answer


I didn't find an official way, but the method below works by creating a mapping fragment of column names to column values ​​and then unmarshalling from there .

// Extracts the column name from column metadata for a given column index
func getColumnName(metadata []types.ColumnMetadata, index int) string {
    if index < len(metadata) {
        // We assume the metadata is in the same order as the columns in the record.
        // If the column name is not set or empty, we can fallback to a default naming convention.
        if metadata[index].Name != nil {
            return *metadata[index].Name
        }
        return fmt.Sprintf("column_%d", index)
    }
    // Fallback if the index is out of range of the metadata slice.
    return fmt.Sprintf("unknown_column_%d", index)
}

// Converts query results to JSON bytes for easy unmarshaling to structs
func queryResultsToJSON(query_results *redshiftdata.GetStatementResultOutput) ([]byte, error) {
    // Convert the records to a slice of maps for JSON conversion
    var records []map[string]interface{}

    for _, row := range query_results.Records {
        record := make(map[string]interface{})
        for idx, col := range row {
            // Use the column metadata to determine the name of the column
            columnName := getColumnName(query_results.ColumnMetadata, idx)

            // Check the type of the value and assign it to the record map
            var value interface{}
            switch v := col.(type) {
            case *types.FieldMemberBlobValue:
                value = v.Value
            case *types.FieldMemberBooleanValue:
                value = v.Value
            case *types.FieldMemberDoubleValue:
                value = v.Value
            case *types.FieldMemberIsNull:
                value = nil
            case *types.FieldMemberLongValue:
                value = v.Value
            case *types.FieldMemberStringValue:
                value = v.Value
            }
            record[columnName] = value
        }
        records = append(records, record)
    }

    // Marshal the records to JSON
    jsonBytes, err := json.Marshal(records)
    if err != nil {
        log.Error("failed to marshal records to JSON, " + err.Error())
        return nil, err
    }

    return jsonBytes, nil
}

The above is the detailed content of Convert AWS redshiftdataapiservice.GetStatementResultOutput to JSON or structure. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
How do you use the pprof tool to analyze Go performance?How do you use the pprof tool to analyze Go performance?Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

How do you write unit tests in Go?How do you write unit tests in Go?Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

How do I write mock objects and stubs for testing in Go?How do I write mock objects and stubs for testing in Go?Mar 10, 2025 pm 05:38 PM

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

How can I define custom type constraints for generics in Go?How can I define custom type constraints for generics in Go?Mar 10, 2025 pm 03:20 PM

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

Explain the purpose of Go's reflect package. When would you use reflection? What are the performance implications?Explain the purpose of Go's reflect package. When would you use reflection? What are the performance implications?Mar 25, 2025 am 11:17 AM

The article discusses Go's reflect package, used for runtime manipulation of code, beneficial for serialization, generic programming, and more. It warns of performance costs like slower execution and higher memory use, advising judicious use and best

How do you use table-driven tests in Go?How do you use table-driven tests in Go?Mar 21, 2025 pm 06:35 PM

The article discusses using table-driven tests in Go, a method that uses a table of test cases to test functions with multiple inputs and outcomes. It highlights benefits like improved readability, reduced duplication, scalability, consistency, and a

How can I use tracing tools to understand the execution flow of my Go applications?How can I use tracing tools to understand the execution flow of my Go applications?Mar 10, 2025 pm 05:36 PM

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization

How do you specify dependencies in your go.mod file?How do you specify dependencies in your go.mod file?Mar 27, 2025 pm 07:14 PM

The article discusses managing Go module dependencies via go.mod, covering specification, updates, and conflict resolution. It emphasizes best practices like semantic versioning and regular updates.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),