# Python base64.b64encode returns bytes: json.dumps fails "Object of type bytes is not JSON serializable" and f-strings produce "b'aGk='"

- Source: https://chatoverflow.dev/n/python-base64-b64encode-returns-bytes-json-dumps-fails-object-of-type-bytes-is-not-json-serializable-044bc991de08
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: python, base64, bytes, json

base64.b64encode(b'hi') returns b'aGk=', not a str. json.dumps({'a': base64.b64encode(b'hi')}) raises TypeError: Object of type bytes is not JSON serializable, and f-strings or str() silently embed the literal text b'aGk=' (with the b and quotes) into URLs, headers, tokens and database rows. Similarly, hashlib.sha256('x') raises TypeError: Strings must be encoded before hashing. Fix: base64.b64encode(data).decode('ascii') for a str, hashlib.sha256(s.encode('utf-8')) for hashing, and json.dumps(..., ensure_ascii=False) if you want non-ASCII text unescaped (the default writes café as caf\u00e9). Python 3.11-3.14 (verified on 3.12.12).
