unmarshall simple json data with golang

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

unmarshall simple json data with golang

问题

以下是翻译好的内容:

以下程序为我提供了所需的输出(ccc09e)。但是这种方法是否正确或者是否可以改进呢?

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type People struct {
  7. Name string
  8. }
  9. func main() {
  10. empJson := `[{"name":"ccc09e"}]`
  11. var emp []People
  12. json.Unmarshal([]byte(empJson), &emp)
  13. s := fmt.Sprintf("%v", emp[0])
  14. s = s[1 : len(s)-1]
  15. fmt.Println(s)
  16. }

我得到了所需的输出 https://go.dev/play/p/L2IJp-ehA2S ,但我需要改进这个程序。

英文:

https://go.dev/play/p/L2IJp-ehA2S

The following program provides me the required output (ccc09e). But this is correct approach or this can be improved.

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type People struct {
  7. Name string
  8. }
  9. func main() {
  10. empJson := `[{"name":"ccc09e"}]`
  11. var emp []People
  12. json.Unmarshal([]byte(empJson), &emp)
  13. s := fmt.Sprintf("%v", emp[0])
  14. s = s[1 : len(s)-1]
  15. fmt.Println(s)
  16. }

I got the required output https://go.dev/play/p/L2IJp-ehA2S and I need improvement to the program.

答案1

得分: 1

看起来你想要获取sPeople数组的第一个元素的Name

不需要进行字符串操作,直接访问即可。

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type People struct {
  7. Name string
  8. }
  9. func main() {
  10. empJson := `[{"name":"ccc09e"}]`
  11. var emp []People
  12. json.Unmarshal([]byte(empJson), &emp)
  13. s := emp[0].Name
  14. fmt.Println(s)
  15. }

https://go.dev/play/p/O2hiGuSyM53

英文:

Looks like you want the Name of the First element of People array in s

No need to do string manipulations. Just access it directly

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type People struct {
  7. Name string
  8. }
  9. func main() {
  10. empJson := `[{"name":"ccc09e"}]`
  11. var emp []People
  12. json.Unmarshal([]byte(empJson), &emp)
  13. s := emp[0].Name
  14. fmt.Println(s)
  15. }

https://go.dev/play/p/O2hiGuSyM53

huangapple
  • 本文由 发表于 2022年9月9日 22:57:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/73664058.html
匿名

发表评论

匿名网友

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

确定