如何在Go语言中构建一个嵌套的、动态的JSON结构。

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

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

huangapple
  • 本文由 发表于 2022年5月13日 21:55:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/72230748.html
匿名

发表评论

匿名网友

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

确定