英文:
how to build a nested, dynamic JSON in Go
问题
我正在使用Go编写一个简单的API,它从数据库中读取数据并输出GeoJSON。
我已经成功实现了对简单点的处理。但是我的一些数据是线(linestring)。我想要有一个通用的GeoJSON结构定义。然而,根据GeoJSON的规定,“Features”元素有一个“Coordinates”子元素,它可以包含一个[2]float32类型的点坐标,或者是线和多边形的点数组。
在Go中有没有一种方法可以定义这样的结构?我来自PHP,那里有弱类型数组,这样的操作非常简单。
如果我不能使用结构体,除了拼接字符串之外,在Go中还有什么其他适当的方法吗?
注意:类似的问题都是关于从动态JSON进行解组。我需要根据数据库内容构建一个GeoJSON。
英文:
I'm writing a simple API in Go that reads from a database and outputs GeoJSON.
I have this working for simple points. But some of my data is lines (linestring). I would like to have a generic GeoJSON struct definition. However, as specified in GeoJSON, the "Features" element has a "Coordinates" sub-element, which contains either a [2]float32 point coordinates, OR an array of points for lines and polygons.
Is there a way to define a struct in Go in such a way? I come from PHP and with the weakly typed arrays there it would be trivial.
If I can't do it with a struct - what else except puzzling together a string is the proper approach in Go?
Note: Similar questions are all about unmarshaling a dynamic JSON. I need to build one from the database contents.
答案1
得分: 2
你可以创建一个map[string]any
,为Coordinates
设置其值,然后进行编组(marshal)操作。例如,可以按照以下方式进行操作:
package main
import (
"encoding/json"
"fmt"
)
type Point struct {
X, Y int
}
func main() {
m := map[string]interface{}{}
var singleCoordinate bool
if singleCoordinate {
m["Coordinates"] = []float32{1, 2}
} else {
m["Coordinates"] = []Point{{X: 1, Y: 2}, {X: 2, Y: 2}}
}
data, err := json.Marshal(m)
fmt.Println(string(data), err)
}
Playground: https://go.dev/play/p/8mJHJ-e-kyX
英文:
You can create a map[string]any
, set its value for Coordinates
and then marshal that.
Like this for example:
package main
import (
"encoding/json"
"fmt"
)
type Point struct {
X, Y int
}
func main() {
m := map[string]any{}
var singleCoordinate bool
if singleCoordinate {
m["Coordinates"] = []float32{1, 2}
} else {
m["Coordinates"] = []Point{{X: 1, Y: 2}, {X: 2, Y: 2}}
}
data, err := json.Marshal(m)
fmt.Println(string(data), err)
}
Playground: https://go.dev/play/p/8mJHJ-e-kyX
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论