gpt4 book ai didi

json - Golang解码数组给出运行时错误: index out of range

转载 作者:行者123 更新时间:2023-12-01 22:06:34 24 4
gpt4 key购买 nike

我是golang的新手,仍然在学习东西,但是在这个问题上我迷迷糊糊。我有从api获取的json数据。 json的相关部分如下所示:

{
"features": [
{
"properties": {
"display_name": "name",
"address": {"county": "County", "country":"country", "country_code":"cc"}
},
"bbox": [13.9171885,44.2603464,15.2326512,45.6729436],
"geometry": {
"coordinates": [
[
[
[14.4899021,41.4867039],
[14.5899021,41.5867039]
]
],
[
[
[15.4899021,41.4867039],
[15.5899021,41.5867039]
]
],
]
}
}
]
}

我试图用这种结构来解码它:
// Feature struct
type Feature struct {
Properties struct {
Name string `json:"display_name"`
Address struct {
Country string `json:"country"`
Code string `json:"country_code"`
} `json:"address"`
} `json:"properties"`
Bbox []float64 `json:"bbox"`
Geo struct {
Coordinates [][][][]float64 `json:"coordinates"`
} `json:"geometry"`
}

// GeoJSONEntry struct
type GeoJSONEntry struct {
Features []Feature `json:"features"`
}

我正在使用此函数调用api:
func (server *Server) ImportRegionsMultiPolygon(w http.ResponseWriter, r *http.Request) {
var locations []LocationMulti
var errors []error

for _, county := range multiPolygons {
res, err := http.Get(baseURL + "?osm_ids=" + county.Type + county.OsmID + "&format=json&polygon_geojson=1")
if err != nil {
errors = append(errors, err)
}

bytes, err := ioutil.ReadAll(res.Body)

if err != nil {
errors = append(errors, err)
}

location, err := ParseGeoJSON(bytes)

if err != nil {
errors = append(errors, err)
} else {
locations = append(locations, location)
}
}

if errors != nil {
http.Error(w, errors[0].Error(), http.StatusBadRequest)
return
} else {
file, _ := json.MarshalIndent(locations, "", " ")
if err := ioutil.WriteFile("./static/regions/geodata-multi.json", file, 0644); err != nil {
http.Error(w, "Error writing file", http.StatusBadRequest)
return
} else {
responses.JSON(w, http.StatusCreated, locations)
}
}
}
LocationMulti如下所示:
// LocationMulti struct
type LocationMulti struct {
Name string
Lat string
Lng string
Country string
CountryCode string
Coordinates [][][][]float64
}

函数 ParseGeoJSON看起来像这样:
func ParseGeoJSON(bytes []byte) (LocationMulti, error) {
var entry GeoJSONEntry
var err error

if err := json.Unmarshal(bytes, &entry); err != nil {
fmt.Println("Error parsing json", err)
}

fmt.Printf("%v\n", &entry)

location := LocationMulti{
Name: entry.Features[0].Properties.Name,
Lat: fmt.Sprintf("%f", (entry.Features[0].Bbox[1]+entry.Features[0].Bbox[3])/2),
Lng: fmt.Sprintf("%f", (entry.Features[0].Bbox[0]+entry.Features[0].Bbox[2])/2),
Country: entry.Features[0].Properties.Address.Country,
CountryCode: entry.Features[0].Properties.Address.Code,
Coordinates: entry.Features[0].Geo.Coordinates,
}

return location, err
}

我收到一个错误:
Error parsing json json: cannot unmarshal array into Go value of type controllers.Entry
2020/04/28 17:36:39 http: panic serving [::1]:61457: runtime error: index out of range

我做错了什么,该如何解码此类json?

最佳答案

Unmarshal方法本身已正确调用,问题是您请求的是JSON格式,该格式是数组而不是预期的GeoJSON。替换json.Unmarshal返回的错误的解决方案

    res, err := http.Get(baseURL + "?osm_ids=" + county.Type + county.OsmID + "&format=json&polygon_geojson=1")


    res, err := http.Get(baseURL + "?osm_ids=" + county.Type + county.OsmID + "&format=geojson&polygon_geojson=1")

编辑:虽然另外我会重写 ParseGeoJSON以避免 panic :
func ParseGeoJSON(bytes []byte) (LocationMulti, error) {
var entry Entry
var err error

if err := json.Unmarshal(bytes, &entry); err != nil {
fmt.Println("Error parsing json", err)
return LocationMulti{}, err
}

fmt.Printf("%v\n", &entry)

if len(entry.Features) == 0 {
return LocationMulti{}, fmt.Errorf("parsed entry has no features")
}

feature := entry.Features[0]
if len(feature.Bbox) < 4 {
return LocationMulti{}, fmt.Errorf("bbox of parsed entry has too few points")
}

location := LocationMulti{
Name: feature.Properties.Name,
Lat: fmt.Sprintf("%f", (feature.Bbox[1]+feature.Bbox[3])/2),
Lng: fmt.Sprintf("%f", (feature.Bbox[0]+feature.Bbox[2])/2),
Country: feature.Properties.Address.Country,
CountryCode: feature.Properties.Address.Code,
Coordinates: feature.Geo.Coordinates,
}

return location, err
}

关于json - Golang解码数组给出运行时错误: index out of range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61484393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com