我一直在努力从数组创建一个嵌套的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)
}
答案 0 :(得分:0)
您定义了' Weight_Data'作为struct的数组
type Weight_Data [] struct {...}
并将其用作[]Weight_Data
结构中的AutoGenerated
字段。这使它成为struct数组的数组,即[][]struct{...}
。我在下面的可执行代码示例中更正了这个错误。
package main
import (
"encoding/json"
"fmt"
)
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 current_weight []Weight_Data
current_weight = append(current_weight, Weight_Data{
Weight_Date: "2017-11-17 15:22:59 -0600 CST",
Weight_Kgs: 86.273,
})
current_weight = append(current_weight, Weight_Data{
Weight_Date: "2017-11-14 15:22:59 -0600 CST",
Weight_Kgs: 85.273,
})
final := AutoGenerated{"Success", current_weight}
js, err := json.Marshal(final)
fmt.Println(string(js), err)
}
输出:
{"Status_message":"Success","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}]} <nil>