Golang从S3将JSON读取到内存中的结构中

问题描述 投票:0回答:1

我在S3中有一个JSON文件,采用以下结构的格式:

type StockInfo []struct {
    Ticker         string `json:"ticker"`
    BoughtPrice    string `json:"boughtPrice"`
    NumberOfShares string `json:"numberOfShares"`
}

并且我想将其读取为S3的结构值。在python中,代码如下所示:

import boto3
import json

s3 = boto3.client('s3', 'us-east-1')
obj = s3.get_object(Bucket=os.environ["BucketName"], Key=os.environ["Key"])
fileContents = obj['Body'].read().decode('utf-8')
json_content = json.loads(fileContents)

但是我仍然对如何在Go中实现这一目标感到困惑。我已经走了这么远:

package main

import (
    "archive/tar"
    "bytes"
    "fmt"
    "log"
    "os"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-sdk-go/service/s3/s3manager"
    "github.com/joho/godotenv"
)

type StockInfo []struct {
    Ticker         string `json:"ticker"`
    BoughtPrice    string `json:"boughtPrice"`
    NumberOfShares string `json:"numberOfShares"`
}

func init() {
    // loads values from .env into the system
    if err := godotenv.Load(); err != nil {
        log.Print("No .env file found")
    }
    return
}

func main() {
    // Store the PATH environment variable in a variable
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-east-1")},
    )
    if err != nil {
        panic(err)
    }

    s3Client := s3.New(sess)
    bucket := "ian-test-bucket-go-python"
    key := "StockInfo.json"

    requestInput := &s3.GetObjectInput{
        Bucket: aws.String(bucket),
        Key:    aws.String(key),
    }
    result, err := s3Client.GetObject(requestInput)
        if err != nil {
             fmt.Println(err)
        }
    fmt.Println(result)

这将返回body / object缓冲区,但是我不确定如何将其读取为字符串,因此可以将其编组为我的结构。我在类似的问题中找到了此代码:

    requestInput := &s3.GetObjectInput{
        Bucket: aws.String(bucket),
        Key:    aws.String(key),
    }

    buf := new(aws.WriteAtBuffer)
    numBytes, _ := *s3manager.Downloader.Download(buf, requestInput)
    tr := tar.NewReader(bytes.NewReader(buf.Bytes()))

但出现以下错误:

not enough arguments in call to method expression s3manager.Downloader.Download
    have (*aws.WriteAtBuffer, *s3.GetObjectInput)
    want (s3manager.Downloader, io.WriterAt, *s3.GetObjectInput, ...func(*s3manager.Downloader))

multiple-value s3manager.Downloader.Download() in single-value context

有人能指出我正确的方向吗?与python相比,这样做似乎有点令人沮丧。

json amazon-web-services go amazon-s3 unmarshalling
1个回答
0
投票
我能够使用以下代码来做到这一点:
© www.soinside.com 2019 - 2024. All rights reserved.