英文:
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
看起来你想要获取s
中People
数组的第一个元素的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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论