panic: interface conversion: interface {} is []interface {}, not string

type testJSON struct {
	Id      string `json:"@id"`
	Type    string `json:"@type"`
	Date    string `json:"dc:date"`
	Context string `json:"@context"`
	Title   string `json:"dc:title"`
	Note    string `json:"odpt:note"`
	Regions struct {
		Type        string `json:"type"`
		Coordinates []interface{}
	} `json:"ug:region"`
	Owl              string `json:"owl:sameAS"`
	Pattern          string `json:"odpt:pattern"`
	Busroute         string `json:"odpt:busroute"`
	Operator         string `json:"odpt:operator"`
	Direction        string `json:"odpt:direction"`
	BusstopPoleOrder []struct {
		Note        string `json:"odpt:note"`
		Index       int    `json:"odpt:index"`
		BusstopPole string `json:"odpt:busstopPole"`
	} `json:"odpt:busstopPoleOrder"`
}

の、

Coordinates []interface{}

の部分をsrting型→分割 → float64型に戻して処理しようしているのですが、

for _, e := range data {
		fmt.Println(e) // 全情報表情
		coors := e.Regions.Coordinates
		fmt.Println("len_mm", len(coors))
		for _, coor := range coors {
			fmt.Println(coor)
			str_coor := coor.(string)
			arr := strings.Split(str_coor, " ")
			lng := arr[0]
			lat := arr[1]
			fmt.Println(lng, lat)
		}
	}

[139.6249873 35.4648941]
panic: interface conversion: interface {} is []interface {}, not string

goroutine 1 [running]:
main.main()
C:/Users/ebata/yoko_bus_route/route_json.go:92 +0x694
exit status 2

というエラーが出てきて停止します ―― キャストできない。

多分対応方法はあると思うのですが、調べるのが面倒なので、C/C++で定番の、あの美しくない方法 "sprintf"を使いました

for _, coor := range coors {

			//	str_coor := coor.(string)   
			str_coor := fmt.Sprintf("%v", coor) // この段階では" [139.575019, 35.439622]"という文字列 

			arr := strings.Split(str_coor, " ") // スペース" " で arr[0], arr[1]という文字列に分離する

			str_lng := strings.Replace(arr[0], "[", "", -1) // arr[0] ("[139.575019")から、"["を消す
			str_lat := strings.Replace(arr[1], "]", "", -1) // arr[1] ("35.439622]")から、"]"を消す

			lng64, _ := strconv.ParseFloat(str_lng, 64) // float64に強制的に型変換する
			lat64, _ := strconv.ParseFloat(str_lat, 64) // float64に強制的に型変換する

			fmt.Println("lng:", lng64)
			fmt.Println("lat:", lat64)

		}

動けばいいんですよ、動けば。

2023,江端さんの技術メモ

Posted by ebata