How to convert Base64 to a JSON string in Go

1 Answer

0 votes
package main

import (
    "encoding/base64"
    "encoding/json"
    "fmt"
)

func main() {
    base64String := "ewogICJ1c2VybmFtZSI6ICJPa2FiZSIsCiAgImFnZSI6IDM3Cn0="
    
    // Decode Base64 to plain text
    decodedBytes, err := base64.StdEncoding.DecodeString(base64String)
    if err != nil {
        fmt.Println("Error decoding Base64:", err)
        return
    }
    decodedString := string(decodedBytes)

    // Parse plain text to JSON
    var jsonObject map[string]interface{}
    if err := json.Unmarshal([]byte(decodedString), &jsonObject); err != nil {
        fmt.Println("Error parsing JSON:", err)
        return
    }

    // Convert JSON object to pretty JSON string
    jsonBytes, err := json.MarshalIndent(jsonObject, "", "  ")
    if err != nil {
        fmt.Println("Error converting to JSON string:", err)
        return
    }

    fmt.Println("JSON String:\n" + string(jsonBytes))
}



/*
run:
    
JSON String:
{
  "age": 37,
  "username": "Okabe"
}
  
*/

 



answered Dec 8, 2025 by avibootz
...