Golang如何从N长度的数组创建嵌套JSON
Golang如何从N长度的数组创建嵌套JSON 我一直在尝试从数组创建嵌套的JSON,但似乎无法弄清楚如何实现。目前我有以下代码,但无论我做什么,它都无法正常工作,也无法修复。
我正在处理的数组如下所示。请注意,我试图让JSON无论数组长度如何都能正常工作。
[{2017-11-20 13:18:12 -0600 CST 70.261 2 1} {2017-11-20 13:11:15 -0600 CST 70.253 0 1} {2017-11-20 13:08:45 -0600 CST 70.43 0 1} {2017-11-20 13:05:29 -0600 CST 70.32000000000001 0 1} {2017-11-13 15:32:43 -0600 CST 76.354 0 1} {2017-11-13 15:26:41 -0600 CST 86.273 2 1} {2017-11-13 15:22:59 -0600 CST 86.273 2 1}][{2017-11-20 13:18:12 -0600 CST 70.261}]
我希望的输出看起来像这样:
{
"Status_message": "successful",
"Weight_data": [{
"Weight_date": "2017-11-17 15:22:59 -0600 CST",
"Weight_kg": 86.273
}, {
"Weight_date": "2017-11-14 15:22:59 -0600 CST",
"Weight_kg": 85.273
}, {
"Weight_date": "2017-11-12 15:22:59 -0600 CST",
"Weight_kg": 76.273
}, {
"Weight_date": "2017-11-16 15:22:59 -0600 CST",
"Weight_kg": 66.273
}]
我当前的代码如下,有两个结构体:
type AutoGenerated struct {
StatusMessage string `json:"Status_message"`
Weight_Data [] Weight_Data
}
type Weight_Data [] struct {
Weight_Date string `json:"Weight_date"`
Weight_Kgs float64 `json:"Weight_kg"`
}
func main() {
var mainStruct AutoGenerated
var current_weight [] Weight_Datas
for i, _ := range m.ParseData().Weights {
current_weight = Weight_Datas{m.ParseData().Weights[i].Date.String(),m.ParseData().Weights[i].Kgs}
mainStruct.Weight_Datas = append(mainStruct.Weight_Datas, current_weight)
}
final := AutoGenerated{"Success",current_weight}
js, err := json.Marshal(final)
}
更多关于Golang如何从N长度的数组创建嵌套JSON的实战教程也可以访问 https://www.itying.com/category-94-b0.html
现在你有两个答案:一个来自 @calmh,另一个在 Stack Overflow 上。
哪个对你更有帮助?
更多关于Golang如何从N长度的数组创建嵌套JSON的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
欢迎来到社区!你的示例代码在类型和变量方面有些混淆,我已经进行了修正。你的类型定义应该像这样:
type AutoGenerated struct {
StatusMessage string `json:"Status_message"`
Weights []WeightData `json:"Weight_data"`
}
type WeightData struct {
Date time.Time `json:"Weight_date"`
Kgs float64 `json:"Weight_kg"`
}
在顶层结构体中,你有一个状态消息字段(string类型)和一个权重字段(WeightData切片类型)。虽然在Go中我们不使用snake_case命名法,但你当然可以在JSON表示中使用它。
WeightData类型应该是一个简单的结构体,而不是切片本身。因此我移除了你类型声明中的方括号(之前是type Weight_Data [] struct ...)。Date属性最好使用实际的time.Time类型,JSON编码器/解码器会处理这里的格式化问题。
("AutoGenerated"这个名称当然应该换个更好的名字,但我暂时保留它。)
在主程序中,我们只需声明一个顶层结构体的实例,然后通过循环向其中添加权重数据。你之前每种类型都有两个,这是不必要的,而且在类型匹配上也有问题。
mainStruct := AutoGenerated{StatusMessage: "Success"}
for i := 0; i < 5; i++ {
w := WeightData{time.Now(), rand.Float64() * 25}
mainStruct.Weights = append(mainStruct.Weights, w)
}
js, _ := json.MarshalIndent(mainStruct, "", " ")
fmt.Printf("%s\n", js)
(我使用了随机数据来代替你从其他地方获取的数据。)结果大致符合你的需求:
{
"Status_message": "Success",
"Weight_data": [
{
"Weight_date": "2009-11-10T23:00:00Z",
"Weight_kg": 15.116507199490488
},
{
"Weight_date": "2009-11-10T23:00:00Z",
"Weight_kg": 23.512727201125312
},
...
可运行代码:
在您的代码中,有几个关键问题需要解决。主要问题在于结构体定义不匹配、字段名称不一致以及JSON序列化逻辑错误。以下是修正后的代码:
package main
import (
"encoding/json"
"fmt"
"time"
)
// 定义主结构体
type AutoGenerated struct {
StatusMessage string `json:"Status_message"`
WeightData []WeightData `json:"Weight_data"`
}
// 定义权重数据结构体
type WeightData struct {
WeightDate string `json:"Weight_date"`
WeightKgs float64 `json:"Weight_kg"`
}
// 模拟数据解析函数
type ParsedData struct {
Weights []struct {
Date time.Time
Kgs float64
}
}
func ParseData() ParsedData {
return ParsedData{
Weights: []struct {
Date time.Time
Kgs float64
}{
{time.Date(2017, 11, 20, 13, 18, 12, 0, time.FixedZone("CST", -6*3600)), 70.261},
{time.Date(2017, 11, 20, 13, 11, 15, 0, time.FixedZone("CST", -6*3600)), 70.253},
{time.Date(2017, 11, 20, 13, 8, 45, 0, time.FixedZone("CST", -6*3600)), 70.43},
},
}
}
func main() {
var mainStruct AutoGenerated
mainStruct.StatusMessage = "successful"
// 处理权重数据
parsedData := ParseData()
for _, weight := range parsedData.Weights {
weightData := WeightData{
WeightDate: weight.Date.String(),
WeightKgs: weight.Kgs,
}
mainStruct.WeightData = append(mainStruct.WeightData, weightData)
}
// 序列化为JSON
js, err := json.MarshalIndent(mainStruct, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(js))
}
运行此代码将输出:
{
"Status_message": "successful",
"Weight_data": [
{
"Weight_date": "2017-11-20 13:18:12 -0600 CST",
"Weight_kg": 70.261
},
{
"Weight_date": "2017-11-20 13:11:15 -0600 CST",
"Weight_kg": 70.253
},
{
"Weight_date": "2017-11-20 13:08:45 -0600 CST",
"Weight_kg": 70.43
}
]
}
主要修正点:
- 修正了结构体定义:
WeightData现在是结构体切片,而不是切片的别名 - 统一了字段名称:使用一致的
WeightData而不是混合的Weight_Data和Weight_Datas - 修正了循环逻辑:直接创建
WeightData实例并追加到切片中 - 使用
json.MarshalIndent获得格式化的JSON输出 - 添加了错误处理
这个解决方案能够处理任意长度的数组,并生成符合您要求的嵌套JSON结构。

