英文:
Converting []uint8/[]byte to hash table GoLang
问题
我的服务器发送的JSON响应如下所示:
{"SortAs": "SGML", "GlossTerm": "标准通用标记语言", "Acronym": "SGML", "Abbrev": "ISO 8879:1986"}
但是我的Go程序接收到的是[]uint8类型。而且从服务器发送的JSON大小不是固定的,它会变化。我该如何将它转换为包含键值对的哈希表?
英文:
My server sends a JSON response which looks like shown below
{"SortAs": "SGML","GlossTerm": "Standard Generalized Markup Language","Acronym": "SGML","Abbrev": "ISO 8879:1986"}
But My Go program receives it as type []uint8 . Also the size JSON sent from the server is not of definite size , it varies . How do i convert it into a Hash table containing key/value pair again ?
答案1
得分: 5
请注意,byte
是 uint8
的别名。根据你的要求,你需要一个简单的 JSON 反序列化操作:
js := []byte(`{"SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986"}`)
m := map[string]interface{}{}
if err := json.Unmarshal(js, &m); err != nil {
panic(err)
}
fmt.Printf("%q", m)
输出结果(换行显示):
map["SortAs":"SGML" "GlossTerm":"Standard Generalized Markup Language"
"Acronym":"SGML" "Abbrev":"ISO 8879:1986"]
你可以在 Go Playground 上尝试运行。
英文:
Note that byte
is an alias for uint8
. Having said that what you want is a simple json unmarshal:
js := []byte(`{"SortAs": "SGML","GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML","Abbrev": "ISO 8879:1986"}`)
m := map[string]interface{}{}
if err := json.Unmarshal(js, &m); err != nil {
panic(err)
}
fmt.Printf("%q",m)
Output (wrapped):
map["SortAs":"SGML" "GlossTerm":"Standard Generalized Markup Language"
"Acronym":"SGML" "Abbrev":"ISO 8879:1986"]
Try it on the Go Playground.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论