将 []uint8/[]byte 转换为哈希表 GoLang

huangapple go评论89阅读模式
英文:

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

请注意,byteuint8 的别名。根据你的要求,你需要一个简单的 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.

huangapple
  • 本文由 发表于 2015年3月23日 13:30:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/29203812.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定