英文:
how to parse response from AWS Go API
问题
我正在使用以下示例程序:
func getEnv(appName string, env string) {
svc := elasticbeanstalk.New(session.New(), &aws.Config{Region: aws.String("us-east-1")})
params := &elasticbeanstalk.DescribeConfigurationSettingsInput{
ApplicationName: aws.String(appName), // Required
EnvironmentName: aws.String(env),
}
resp, err := svc.DescribeConfigurationSettings(params)
if err != nil {
fmt.Println(err.Error())
return
}
v := resp.ConfigurationSettings
fmt.Printf("%s", v)
}
它打印出以下响应;这看起来像一个有效的 JSON,除了缺少引号。例如:ApplicationName 而不是 "ApplicationName"。
我该如何解析它?或者如何从 AWS 获取有效的 JSON?
ConfigurationSettings: [{
ApplicationName: "myApp",
DateCreated: 2016-01-12 00:10:10 +0000 UTC,
DateUpdated: 2016-01-12 00:10:10 +0000 UTC,
DeploymentStatus: "deployed",
Description: "Environment created from the EB CLI using \"eb create\"",
EnvironmentName: "stag-myApp-app-s1",
OptionSettings: [
...
请注意,我只提供翻译服务,不会回答关于翻译内容的问题。
英文:
I am using the following sample program:
func getEnv(appName string, env string) {
svc := elasticbeanstalk.New(session.New(), &aws.Config{Region: aws.String("us-east-1")})
params := &elasticbeanstalk.DescribeConfigurationSettingsInput{
ApplicationName: aws.String(appName), // Required
EnvironmentName: aws.String(env),
}
resp, err := svc.DescribeConfigurationSettings(params)
if err != nil {
fmt.Println(err.Error())
return
}
v := resp.ConfigurationSettings
fmt.Printf("%s", v)
}
It's printing out the following response; this looks like a valid json except for the missing quote makes. ex: ApplicationName and not "ApplicationName".
How do I parse this? or get a valid json from AWS?
ConfigurationSettings: [{
ApplicationName: "myApp",
DateCreated: 2016-01-12 00:10:10 +0000 UTC,
DateUpdated: 2016-01-12 00:10:10 +0000 UTC,
DeploymentStatus: "deployed",
Description: "Environment created from the EB CLI using \"eb create\"",
EnvironmentName: "stag-myApp-app-s1",
OptionSettings: [
...
答案1
得分: 2
resp.ConfigurationSettings
不再是JSON格式,aws-sdk-go
包已经为您处理了这个问题。当您执行以下操作时,
v := resp.ConfigurationSettings
v
包含一个从JSON响应解析出的[]*ConfigurationSettingsDescription
实例,您不需要自己解析它。当您打印它时,您看到的是Go结构的表示。您可以直接使用它:
if len(v) > 0 {
log.Println(v[0].ApplicationName)
}
这将打印出myApp
。
英文:
resp.ConfigurationSettings
is not in JSON format any more, the aws-sdk-go
package handled that for you. When you do,
v := resp.ConfigurationSettings
v
contains an instance []*ConfigurationSettingsDescription
that was parsed from the JSON response, and you don't have to parse it yourself. What you are seeing when you print it out is the Go struct representation. You can just go ahead and use it:
if len(v) > 0 {
log.Println(v[0].ApplicationName)
}
This should print out myApp
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论