简体   繁体   English

如何在 Go 中解码 base64 编码的 JSON

[英]How to decode base64 encoded JSON in Go

I have a map of type map[string][]byte , now the value of []byte is base64 encoded.我有地图的类型的map[string][]byte ,现在的值[]byte是base64编码。 There's a JSON encoded in that []byte that I want to use further.我想进一步使用该[]byte中编码的 JSON。 Now I do this to decode the base64 []byte array.现在我这样做是为了解码 base64 []byte数组。

Assume that my secretInfo looks like this假设我的secretInfo看起来像这样

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.现在,我将 JSON 的值作为字符串传递给其他 JSON。

secretInfo.StringData["DecodedPrivateKeyJson"] = string(bytes)

It throws me an error saying, expected JSON in StringData.DecodedPrivateKeyJson.它向我抛出一个错误,指出 StringData.DecodedPrivateKeyJson 中的预期 JSON。

What am I missing?我错过了什么?

It seems there is some issue in your code above上面的代码中似乎存在一些问题

  1. You ignored the decode error您忽略了解码错误
  2. You have not provided the code for how you parse the secret info您尚未提供有关如何解析机密信息的代码

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)
    }
}

Go Playground去游乐场

Updated same code to use []Byte to provide more clarity更新了相同的代码以使用 []Byte 以提供更清晰的信息

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM