Reputation: 703
I have a map of type map[string][]byte
, now the value of []byte
is base64 encoded.
There's a JSON encoded in that []byte
that I want to use further. Now I do this to decode the base64 []byte
array.
Assume that my secretInfo
looks like this
apiVersion: v1
kind: Secret
metadata:
namespace: kube-system
name: my-credentials
data:
secret_account.json: SGVsbG8sIHBsYXlncm91bmQ= // My base64 encoded data(not real/Actual data)
bytes, _ := b64.StdEncoding.DecodeString(string(secretInfo.Data["secret_account.json"])) // Converting data
var privateKeyJSON map[string]interface{}
err := json.Unmarshal(bytes, &privateKeyJSON)
if err != nil {
r.Logger.Infof("Failed to parse secret %v", err)
}
Now, I pass the value of the JSON to other JSON as a string.
secretInfo.StringData["DecodedPrivateKeyJson"] = string(bytes)
It throws me an error saying, expected JSON in StringData.DecodedPrivateKeyJson.
What am I missing?
Upvotes: 0
Views: 10085
Reputation: 3374
I think the problem is in this line:
secretInfo.StringData["DecodedPrivateKeyJson"] = string(bytes)
Which probably it should be like this:
secretInfo.StringData["DecodedPrivateKeyJson"] = string(privateKeyJSON)
Or event better:
marshaledPrivateKeyJSON, _ := json.Marshal(privateKeyJSON)
secretInfo.StringData["DecodedPrivateKeyJson"] = string(marshaledPrivateKeyJSON)
Upvotes: 0
Reputation: 1877
It seems there is some issue in your code above
Adding a sample code with few cases, Hope It Helps :)
package main
import (
b64 "encoding/base64"
"encoding/json"
"fmt"
)
func main() {
encodedJSONTestData := []string{
"ewoiZmlyc3RuYW1lIjoiSmhvbiIsCiJsYXN0bmFtZSI6ICJEb2UiCn0=",
"",
"!@#$%rtgfdjkmyhm",
}
for i, encodedJSON := range encodedJSONTestData {
fmt.Println("Case", i)
bytes, err := b64.StdEncoding.DecodeString(encodedJSON) // Converting data
if err!=nil{
fmt.Println("Failed to Decode secret", err)
continue
}
var privateKeyJSON map[string]interface{}
err = json.Unmarshal(bytes, &privateKeyJSON)
if err != nil {
fmt.Println("Failed to parse secret", err)
continue
}
fmt.Println("Success", privateKeyJSON)
}
}
Updated same code to use []Byte to provide more clarity
Upvotes: 1