Reputation: 61
I am trying to parse a JSON of the type
"{\"ids\":[\"a\",\"b\"]}"
Here is my code:
package main
import "fmt"
import "encoding/json"
import "strings"
type Idlist struct {
id []string `json:"ids"`
}
func main() {
var val []byte = []byte(`"{\"ids\":[\"a\",\"b\"]}"`)
jsonBody, _ := strconv.Unquote(string(val))
var holder Idlist
if err := json.NewDecoder(strings.NewReader(jsonBody)).Decode(&holder); err!= nil{
fmt.Print(err)
}
fmt.Print(holder)
fmt.Print(holder.id)
}
However, I keep getting output
{[]}[]
I cannot get the data in the structure. Where am I going wrong? Here is the playground link: https://play.golang.org/p/82BaUlfrua
Upvotes: 0
Views: 511
Reputation: 157
This is example how you can resolve your problem: http://play.golang.org/p/id4f4r9tEr
You might need to use strconv.Unquote
on your string.
And this is probably duplicate: How to unmarshal an escaped JSON string in Go?
Resolved: https://play.golang.org/p/hAShmfDUA_
type Idlist struct {
Id []string `json:"ids"`
}
Upvotes: 0
Reputation: 88
Your struct has to look like :
type Idlist struct {
Id []string `json:"ids"`
}
Golang assumes that the fields starting with capital case are public. Hence, your fields are not visible to json decoder. For more details please look into this post : Why Golang cannot generate json from struct with front lowercase character?
Upvotes: 1