0

Structs and JSON are not super fun in Go.

I have a simple example of some JSON, and a struct. Everything seems to get parsed Okay, but for some reason the array does not get picked up.

Can anyone tell me what I might be missing.

Code--- package main

import ( "encoding/base64" "fmt" "encoding/json" ) type Oauth struct { Aud string `json:"aud"` Cid string `json:"cid"` Exp int `json:"exp"` Iat int `json:"iat"` Iss string `json:"iss"` Jti string `json:"jti"` Scp []string `json:"scp"` Sub string `json:"sub"` UID string `json:"uid"` Ver int `json:"ver"` } func main () { // This is the String {"ver":1,"jti":"AT.zgv9oQpw-7l3BCg6Xb5NCG2Pf8zxgiQa1EUBXycmaDk","iss":"https://companyx.okta.com/oauth2/aus1a4ibdat0JYw5s1d8","aud":"http://localhost","iat":1484538606,"exp":1484542206,"cid":"3jmNvVCFZ5F6lWOzIONO","uid":"00uy74c0h7NGTLBSXQOC","scp":["read","remove","reserve"],"sub":"[email protected]"} encoded := "eyJ2ZXIiOjEsImp0aSI6IkFULnpndjlvUXB3LTdsM0JDZzZYYjVOQ0cyUGY4enhnaVFhMUVVQlh5Y21hRGsiLCJpc3MiOiJodHRwczovL2NvbXBhbnl4Lm9rdGEuY29tL29hdXRoMi9hdXMxYTRpYmRhdDBKWXc1czFkOCIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3QiLCJpYXQiOjE0ODQ1Mzg2MDYsImV4cCI6MTQ4NDU0MjIwNiwiY2lkIjoiM2ptTnZWQ0ZaNUY2bFdPeklPTk8iLCJ1aWQiOiIwMHV5NzRjMGg3TkdUTEJTWFFPQyIsInNjcCI6WyJyZWFkIiwicmVtb3ZlIiwicmVzZXJ2ZSJdLCJzdWIiOiJva3RhYWRtaW5Ab2t0YS5jb20ifQ" data, _ := base64.StdEncoding.DecodeString(encoded) fmt.Println(string(data)) fmt.Println ("") var x Oauth json.Unmarshal([]byte(data), &x) fmt.Printf ("%+v",x.Scp); } 

The result is always an Empty Array []

1
  • I put the code on GoLang Playground to make it easier to see what I'm seeing: play.golang.org/p/Pebw7UgGRC Commented Jan 16, 2017 at 4:39

2 Answers 2

2

The encoded string isn't a valid JSON, easy to detect because you're ignoring an important error on Unmarshal, try this:

err := json.Unmarshal(data, &x) fmt.Println(err) 

It looks like you missed the last '}' of your JSON.

Sign up to request clarification or add additional context in comments.

Comments

0

Your base64-encoded string is not valid:

illegal base64 data at input byte 404 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.