3 回答

TA貢獻2011條經驗 獲得超2個贊
您需要使用“encoding/json”包中的 Unmarshal 函數并使用虛擬結構來提取切片字段
// You can edit this code!
// Click here and start typing.
package main
import (
"encoding/json"
"fmt"
)
func main() {
str := `{"Responses":[{"type":"DROP_DOWN","value":"0"}]}`
type Responses struct {
Type string `json:"type"`
Value string `json:"value"`
}
// add dummy struct to hold responses
type Dummy struct {
Responses []Responses `json:"Responses"`
}
var res Dummy
err := json.Unmarshal([]byte(str), &res)
if err != nil {
panic(err)
}
fmt.Println("%v", len(res.Responses))
fmt.Println("%s", res.Responses[0].Type)
fmt.Println("%s", res.Responses[0].Value)
}

TA貢獻1863條經驗 獲得超2個贊
JSON-to-go是一個很好的在線資源,可以為特定的 JSON 模式制作 Go 日期類型。
粘貼您的 JSON 正文并提取嵌套類型,您可以使用以下類型生成所需的 JSON 模式:
// types to produce JSON:
//
// {"Responses":[{"type":"DROP_DOWN","value":"0"}]}
type FruitBasket struct {
Response []Attr `json:"Responses"`
}
type Attr struct {
Type string `json:"type"`
Value string `json:"value"`
}
使用:
form := FruitBasket{
Response: []Attr{
{
Type: "DROP_DOWN",
Value: "0",
},
}
}
jsonData, err := json.Marshal(form)
工作示例:https ://go.dev/play/p/SSWqnyVtVhF
輸出:
{"Responses":[{"type":"DROP_DOWN","value":"0"}]}

TA貢獻1829條經驗 獲得超4個贊
您的結構不正確。你的標題想要字典,但你寫了一個數組或字符串片段。
從此更改您的 FruitBasket 結構:
type FruitBasket struct {
Name5 []string `json:"Responses"`
}
對此
type FruitBasket struct {
Name5 []map[string]interface{} `json:"Responses"`
}
map[string]interface{}是字典嗎
這是游樂場https://go.dev/play/p/xRSDGdZYfRN
- 3 回答
- 0 關注
- 195 瀏覽
添加回答
舉報