unmarshall simple json data with golang

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

unmarshall simple json data with golang

问题

以下是翻译好的内容:

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

package main

import (
	"encoding/json"
	"fmt"
)

type People struct {
	Name string
}

func main() {
	empJson := `[{"name":"ccc09e"}]`
	var emp []People
	json.Unmarshal([]byte(empJson), &emp)
	s := fmt.Sprintf("%v", emp[0])
	s = s[1 : len(s)-1]
	fmt.Println(s)
}

我得到了所需的输出 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.

package main

import (
	"encoding/json"
	"fmt"
)

type People struct {
	Name string
}

func main() {
	empJson := `[{"name":"ccc09e"}]`
	var emp []People
	json.Unmarshal([]byte(empJson), &emp)
	s := fmt.Sprintf("%v", emp[0])
	s = s[1 : len(s)-1]
	fmt.Println(s)
}

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

答案1

得分: 1

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

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

package main

import (
	"encoding/json"
	"fmt"
)

type People struct {
	Name string
}

func main() {
	empJson := `[{"name":"ccc09e"}]`
	var emp []People
	json.Unmarshal([]byte(empJson), &emp)
	s := emp[0].Name
	fmt.Println(s)
}

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

package main

import (
	"encoding/json"
	"fmt"
)

type People struct {
	Name string
}

func main() {
	empJson := `[{"name":"ccc09e"}]`
	var emp []People
	json.Unmarshal([]byte(empJson), &emp)
	s := emp[0].Name
	fmt.Println(s)
}

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:

确定