无法解析 Golang 中的 JSON 数组。

huangapple go评论92阅读模式
英文:

Unable to parse JSON array in Golang

问题

我正在努力解析以下JSON数组。

// JSON数组
[      
  {
    "ShaId": "adf56a4d",
    "Regions": [
      {
        "Name": "us-east-1a"
      }
    ]
  }
 .... 更多类似的
]     

Go Playground链接:https://play.golang.org/p/D4VrX3uoE8

我在哪里犯了错误?

英文:

I am having hard time parsing following JSON array.

// JSON Array
[      
  {
    "ShaId": "adf56a4d",
    "Regions": [
      {
        "Name": "us-east-1a"
      }
    ]
  }
 .... more such
]     

Link to Go Playground :- https://play.golang.org/p/D4VrX3uoE8

Where am I making mistake?

答案1

得分: 2

这是您的原始JSON输入:

content := `{"ShaId": "adf56a4d", "Regions": [{"Name": "us-east-1a"}]}`

它不是一个数组,将其改为:

content := `[{"ShaId": "adf56a4d", "Regions": [{"Name": "us-east-1a"}]}]`

使用这个结果:

Results: []main.ShaInfo{main.ShaInfo{ShaId:"adf56a4d",
                Regions:main.Region{struct { Name string }{Name:"us-east-1a"}}}}

注意:

如果您的输入不是一个数组,则不要尝试从中解析出一个数组(切片),只需一个ShaInfo。如果您不能修改输入,这也适用:

var data ShaInfo
content := `{"ShaId": "adf56a4d", "Regions": [{"Name": "us-east-1a"}]}` 
json.Unmarshal([]byte(content), &data)

输出:

Results: main.ShaInfo{ShaId:"adf56a4d",
              Regions:main.Region{struct { Name string }{Name:"us-east-1a"}}}
英文:

This is your original JSON input:

content := `{"ShaId": "adf56a4d", "Regions": [{"Name": "us-east-1a"}]}`

It is not an array, change it to:

content := `[{"ShaId": "adf56a4d", "Regions": [{"Name": "us-east-1a"}]}]`

With this, the result:

Results: []main.ShaInfo{main.ShaInfo{ShaId:"adf56a4d",
                Regions:main.Region{struct { Name string }{Name:"us-east-1a"}}}}

Note:

If you input is not an array, then don't try to parse an array (slice) out of it, just one ShaInfo. This also works if you don't/can't modify the input:

var data ShaInfo
content := `{"ShaId": "adf56a4d", "Regions": [{"Name": "us-east-1a"}]}`
json.Unmarshal([]byte(content), &data)

Output:

Results: main.ShaInfo{ShaId:"adf56a4d",
              Regions:main.Region{struct { Name string }{Name:"us-east-1a"}}}

huangapple
  • 本文由 发表于 2015年3月20日 19:00:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/29164967.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定