user3888307
user3888307

Reputation: 3133

GO Lang decode JSON (simple array not being picked up)

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 []

Upvotes: 0

Views: 134

Answers (2)

Yandry Pozo
Yandry Pozo

Reputation: 5123

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.

Upvotes: 2

Alex Pliutau
Alex Pliutau

Reputation: 21937

Your base64-encoded string is not valid:

illegal base64 data at input byte 404

Upvotes: 0

Related Questions