JSON data expects to handle Unicode strings. Binary image data (in the form of a bytes object) is not text, so when the json.dumps() function tries to process the data it throws an error.

You'll have to wrap your binary data in a text-safe encoding first, such as Base64:

import base64

json.dumps({'picture' : base64.b64encode(data).decode()})

Of course, this then assumes that the receiver expects your data to be wrapped so.

If your API endpoint has been so badly designed to expect your image bytes to be passed in as text, then the alternative is to pretend that your bytes are really text; if you first decode it as Latin-1 you can map those bytes straight to Unicode codepoints:

json.dumps({'picture' : data.decode('latin-1')})

This happens to work because the Latin-1 encoding can represent all 256 possible byte values.

With the data as a str object the json library will then proceed to treat it as text. This does mean that it can replace non-ASCII codepoints with \uhhhh escapes. Again, the receiver of the JSON payload must also expect the data to be encoded this way for this to work.

Answer from Martijn Pieters on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-bytes-to-json-using-python
Convert Bytes To Json using Python - GeeksforGeeks
July 23, 2025 - In this example, we use the json.loads() method and decode() method to convert bytes to JSON objects. ... import json # Complex byte data byte_data = b'{"name": "John", "age": 30, "city": "New York", ...
Discussions

python - Convert a bytes array into JSON format - Stack Overflow
I want to parse a bytes string in JSON format to convert it into python objects. This is the source I have: my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\'... More on stackoverflow.com
🌐 stackoverflow.com
October 17, 2020
Send bytes in json format to the server in socket programming python - Stack Overflow
I wrote a socket What I want to do is select a file After that, read the file and after that convert the readed file to a list and building a list of bytes And every time I send one of the indexes of More on stackoverflow.com
🌐 stackoverflow.com
python - Send bytes encoded data over JSON - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I'm working on an Python RESTful API and I need to send bytes-encoded data (specifically data encrypted using a public RSA key from the package rsa) over the network, via JSON forms. More on stackoverflow.com
🌐 stackoverflow.com
April 20, 2020
python - How to encode bytes in JSON? json.dumps() throwing a TypeError - Stack Overflow
I am trying to encode a dictionary containing a string of bytes with json, and getting a is not JSON serializable error: import base64 import json data = {} encoded = base64.b64encode(b'data to be More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python
bugs.python.org › issue10976
Issue 10976: accept bytes in json.loads() - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/55185
Top answer
1 of 9
216

Your bytes object is almost JSON, but it's using single quotes instead of double quotes, and it needs to be a string. So one way to fix it is to decode the bytes to str and replace the quotes. Another option is to use ast.literal_eval; see below for details. If you want to print the result or save it to a file as valid JSON you can load the JSON to a Python list and then dump it out. Eg,

import json

my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

# Decode UTF-8 bytes to Unicode, and convert single quotes 
# to double quotes to make it valid JSON
my_json = my_bytes_value.decode('utf8').replace("'", '"')
print(my_json)
print('- ' * 20)

# Load the JSON to a Python list & dump it back out as formatted JSON
data = json.loads(my_json)
s = json.dumps(data, indent=4, sort_keys=True)
print(s)

output

[{"Date": "2016-05-21T21:35:40Z", "CreationDate": "2012-05-05", "LogoType": "png", "Ref": 164611595, "Classe": ["Email addresses", "Passwords"],"Link":"http://some_link.com"}]
- - - - - - - - - - - - - - - - - - - - 
[
    {
        "Classe": [
            "Email addresses",
            "Passwords"
        ],
        "CreationDate": "2012-05-05",
        "Date": "2016-05-21T21:35:40Z",
        "Link": "http://some_link.com",
        "LogoType": "png",
        "Ref": 164611595
    }
]

As Antti Haapala mentions in the comments, we can use ast.literal_eval to convert my_bytes_value to a Python list, once we've decoded it to a string.

from ast import literal_eval
import json

my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

data = literal_eval(my_bytes_value.decode('utf8'))
print(data)
print('- ' * 20)

s = json.dumps(data, indent=4, sort_keys=True)
print(s)

Generally, this problem arises because someone has saved data by printing its Python repr instead of using the json module to create proper JSON data. If it's possible, it's better to fix that problem so that proper JSON data is created in the first place.

2 of 9
119

You can simply use,

import json

my_bytes_value = my_bytes_value.decode().replace("'", '"')
json.loads(my_bytes_value)
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-a-bytes-array-into-json-format-in-python
Convert a Bytes Array into Json Format in Python - GeeksforGeeks
July 23, 2025 - In this example, we are using decode(), json.loads() and io module to convert a bytes array into JSON format in Python.
🌐
Python Forum
python-forum.io › thread-31323.html
bytes to json
Hi I am trying to send json data over a pipe but cannot get it quite right Send mesages = win32file.WriteFile(handle, str.encode(json.dumps(mesages), encoding="ascii"))receive result, data = win32file
Top answer
1 of 1
2

TCP is a streaming protocol. There are no message boundaries. It is up to you to read the byte stream and parse it for messages.

One easy method is to make a "message" be a newline-terminated string. socket has a .makefile method that wraps the TCP stream in a file-like object. This object has a .readline method. Send each JSON as a newline-terminated line.

Example:

server.py

import socket
import threading
import json

def listen_for_messages(client, address):
    with client.makefile('rb') as rfile:
        while True:
            line = rfile.readline()
            if not line: break
            message = json.loads(line)
            print(f'{address}: {message}')

server = socket.socket()
server.bind(('', 1234))
server.listen()
while True:
    client, address = server.accept()
    threading.Thread(target=listen_for_messages, args=(client, address)).start()

client.py

import socket
import json

with socket.socket() as s:
    s.connect(('localhost', 1234))
    lst = ['abc', 'def', 'ghi']
    for elem in lst:
        dic = json.dumps({'type': 'fileUpload', 'file': elem}) + '\n'
        s.sendall(dic.encode())

Start server.py and run client.py a few times.

Output example:

('127.0.0.1', 21062): {'type': 'fileUpload', 'file': 'abc'}
('127.0.0.1', 21062): {'type': 'fileUpload', 'file': 'def'}
('127.0.0.1', 21062): {'type': 'fileUpload', 'file': 'ghi'}
('127.0.0.1', 21065): {'type': 'fileUpload', 'file': 'abc'}
('127.0.0.1', 21065): {'type': 'fileUpload', 'file': 'def'}
('127.0.0.1', 21065): {'type': 'fileUpload', 'file': 'ghi'}
('127.0.0.1', 21278): {'type': 'fileUpload', 'file': 'abc'}
('127.0.0.1', 21278): {'type': 'fileUpload', 'file': 'def'}
('127.0.0.1', 21278): {'type': 'fileUpload', 'file': 'ghi'}
🌐
TutorialsPoint
tutorialspoint.com › article › How-can-I-convert-a-bytes-array-into-JSON-format-in-Python
How can I convert a bytes array into JSON format in Python?
March 5, 2020 - Once you have the bytes as a string, you can use the JSON.dumps method to convert the string object to JSON.
Find elsewhere
🌐
Hustle Play
hustleplay.wordpress.com › 2010 › 01 › 05 › sending-binary-with-json
Sending Binary with JSON | Hustle Play - WordPress.com
January 5, 2010 - Here is an example in Python: ... Next, you have to do binary-to-text encoding on the binary file because the JSON API will complain if you try to feed it a binary string. To overcome this obstacle, you need to apply Base64 encoding. Base64 is not your only option — you can also use Huffman encoding or Hexadecimal. Here is the Python code to do the Base64 encoding:
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to serialize bytes to json in python
5 Best Ways to Serialize Bytes to JSON in Python - Be on the Right Side of Change
February 23, 2024 - This method involves encoding bytes using the Base64 encoding scheme to convert them into a string that can be easily serialized into JSON. The base64 module in Python provides methods like b64encode and b64decode for encoding and decoding byte data.
🌐
Quora
quora.com › How-do-you-pass-a-byte-array-in-a-JSON-request
How to pass a byte array in a JSON request - Quora
Answer (1 of 3): JSON only has a few data types and raw byte data isn't one of them. It has arrays, decimal numbers, strings, and objects. So you really have three choices: 1. An array of numbers. Each number could represent one byte, two bytes, or four bytes (since JavaScript's max safe integer...
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.8 documentation
Unlike pickle and marshal, JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to dump() using the same fp will result in an invalid JSON file. ... fp (file-like object) – The file-like object obj will be serialized to. The json module always produces str objects, not bytes objects, therefore fp.write() must support str input.
🌐
The Geek Stuff
thegeekstuff.com › 2021 › 03 › python-json-encode-decode
5 Python Examples to Read and Write JSON files for Encode and Decode
March 31, 2021 - The above code snippet uses python if else format. Refer to this for additional information: 9 Python if, if else, if elif Command Examples · Json module allows the user to parse json in the form of strings, bytes or byte array into dictionary. This is done using function json.loads() .
Top answer
1 of 3
4

The most important part to properly answer this is the information on how you pass these objetcts to the Python2 program: you are using JSON.

So, stay with me:

After you do the .encode step in program 1, you have a bytes object. By calling str(...) on it, you are just putting a escaping layer on this bytes object, and turning it back to a string - but when this string is written as is to a file, or transmited over the network, it will be encoded again - any non-ASCII tokens are usually escaped with the \u prefix and the codepoint for each character - but the original Chinese chracters themselves are now encoded in utf-8 and doubly-escaped.

Python's JSON load methods already decode the contents of json data into text-strings: so a decode method is not to be expected at all.

In short: to pass data around, simply encode your original text as JSON in the first program, and do not botter with any decoding after json.load on the target Python 2 program:

# my first program
x = "宇宙"
# No str-encode-decode dance needed here.
...
data =  json.dumps({"example_key": x, ...})
# code to transmit json string by network or file as it is...


# my other program
text = json.loads(data)["example_key"]
# text is a Unicode text string ready to be used!

As you are doing, you are probably gettint the text doubly-encoded - I will mimick it on the Python 3 console. I will print the result from each step so you can undestand the transforms that are taking place.

In [1]: import json

In [2]: x = "宇宙"

In [3]: print(x.encode("utf-8"))
b'\xe5\xae\x87\xe5\xae\x99'

In [4]: text = str(x.encode("utf-8"))

In [5]: print(text)
b'\xe5\xae\x87\xe5\xae\x99'

In [6]: json_data = json.dumps(text)

In [7]: print(json_data)
"b'\\xe5\\xae\\x87\\xe5\\xae\\x99'"
# as you can see, it is doubly escaped, and it is mostly useless in this form

In [8]: recovered_from_json = json.loads(json_data)

In [9]: print(recovered_from_json)
b'\xe5\xae\x87\xe5\xae\x99'

In [10]: print(repr(recovered_from_json))
"b'\\xe5\\xae\\x87\\xe5\\xae\\x99'"

In [11]: # and if you have data like this in files/databases you need to recover:

In [12]: import ast

In [13]: recovered_text = ast.literal_eval(recovered_from_json).decode("utf-8")

In [14]: print(recovered_text)
宇宙
2 of 3
0

I had this issue when decoding stringified bytes received in a JSON payload:

print(value)
>>> "b'text-here'"

Encoding the string only compounded the problem by adding another layer of wrapping:

encoded = value.encode("utf-8")
print(encoded)
>>> b"b'text-here'"

And this solution from @jsbueno didn't work for me - I got a json.decoder.JSONDecodeError:

recovered_from_json = json.loads(json_data)

SOLUTION

You need to evaluate the string to expose the wrapped bytes object:

import ast

as_bytes = ast.literal_eval(value)
print(as_bytes)
>>> b'text-here'

Then you can decode to string:

decoded = value.decode()
print(decoded)
>>> 'text-here'

As noted by @snakecharmerb, you shouldn't use eval() as it opens you up to running potentially dangerous commands if input is not checked or sanitized (see this old but illustrative blog post)

🌐
Like Geeks
likegeeks.com › home › python › how to convert bytes array to json in python
How To Convert Bytes Array to JSON in Python
January 24, 2024 - We’ll deal with standard UTF-8 encoded JSON, non-UTF encodings, Byte Order Marks (BOM), escaped JSON strings, and even create a custom decoder for specialized data. ... You can use json.loads() to convert the data into a Python dictionary.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-typeerror-the-json-object-must-be-str-bytes-or-bytearray-not-dict
The JSON object must be str, bytes or bytearray, not dict | bobbyhadz
April 8, 2024 - The Python TypeError: the JSON object must be str, bytes or bytearray, not dict occurs when we pass a dictionary to the `json.loads()` method.
🌐
zSecurity
zsecurity.org › home › topics › learn python & ethical hacking from scratch › socket.send() with python3: encoding/decoding str to bytes, json problem
socket.send() with Python3: encoding/decoding str to bytes, JSON problem - zSecurity
April 19, 2020 - * This is what json.loads() does: “Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object” Therefore it can handle bytes, we don’t need to use .decode() first.