How to convert Base64 to a JSON string in Python

1 Answer

0 votes
import base64
import json

def base64_to_pretty_json(base64_string: str) -> str:
    """
    Decode a Base64 string, parse it as JSON, and return a pretty-printed JSON string.
    """
    try:
        # Decode Base64 to plain text
        decoded_bytes = base64.b64decode(base64_string)
        decoded_string = decoded_bytes.decode("utf-8")
 
        # Parse plain text to JSON
        json_object = json.loads(decoded_string)

        # Convert JSON object to pretty JSON string
        return json.dumps(json_object, indent = 2)
    except Exception as e:
        return f"Error converting Base64 to JSON: {e}"


if __name__ == "__main__":
    base64_string = "ewogICJ1c2VybmFtZSI6ICJPa2FiZSIsCiAgImFnZSI6IDM3Cn0="
    
    result = base64_to_pretty_json(base64_string)
    
    print("JSON String:")
    print(result)




'''
run:

JSON String:
{
  "username": "Okabe",
  "age": 37
}

'''

 



answered Dec 8, 2025 by avibootz
...