unmarshall simple json data with golang

Viewed 32

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 Answers

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

Related