golang unmarshal json object into map[string]interface{} by default, how can I unmarshal it into []byte? Because I need secondary unmarshal it into a struct instance after I got its Type.
1条回答 默认 最新
- doushi5752 2015-06-15 08:53关注
Why don't you unmarshal the
json
into the struct directly?Or in case you have more objects into slice of struct?
package main import ( "encoding/json" "fmt" ) type TestJson struct { Foo string Baz string } var ( jsonValue = `{"FOO" : "BAR", "BAZ" : "QUX"}` jsonValueSlice = `[{"FOO" : "BAR", "BAZ" : "QUX"},{"FOO" : "Second BAR", "BAZ" : "Second QUX"}]` ) func main() { t := TestJson{} err := json.Unmarshal([]byte(jsonValue), &t) if err != nil { fmt.Println(err) } fmt.Printf("%+v ", t) t2 := []TestJson{} err2 := json.Unmarshal([]byte(jsonValueSlice), &t2) if err2 != nil { fmt.Println(err2) } fmt.Printf("%+v ", t2) }
EDIT : Go doesn't unmarshal into an map[string]interface{} by default, read the docs!
func Unmarshal(data []byte, v interface{}) error
Golang json.Unmarshal can populate basically anyting, as long your data is consistant.
解决 无用评论 打赏 举报
悬赏问题
- ¥15 一直显示正在等待HID—ISP
- ¥15 Python turtle 画图
- ¥15 关于大棚监测的pcb板设计
- ¥15 stm32开发clion时遇到的编译问题
- ¥15 lna设计 源简并电感型共源放大器
- ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
- ¥15 Vue3地图和异步函数使用
- ¥15 C++ yoloV5改写遇到的问题
- ¥20 win11修改中文用户名路径
- ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入