You can read a file in binary mode as follows: with open('file.json', 'rb') as f: json_binary = file.read() Answer from XUtYwYzz on reddit.com
Top answer
1 of 3
4

In the RFC https://www.rfc-editor.org/rfc/rfc7159, it says:

JSON text SHALL be encoded in UTF-8, UTF-16, or UTF-32

At first glance it does seem that Python isn't really following the spec when you first look at this after all what does it mean to encode something when it remains a Python3 'str' string, however Python is doing some encoding for you nonetheless. Try this:

>>> json.dumps({"Japan":"日本"})
'{"Japan": "\\u65e5\\u672c"}'

You can see that the Japanese has got converted to unicode escapes, and the resultant string is actually ASCII, even if it's still a Python str. I'm unsure how to get json.dumps() to actually give you utf-8 sequences - for interoperability purposes - if you wanted them, however for all practical purposes this is good enough for most people. The characters are there and will be interpreted correctly. It's easy to get binary with:

>>> json.dumps({"Japan":"日本"}).encode("ascii")
b'{"Japan": "\\u65e5\\u672c"}'

And python does the right thing when loading back in:

>>> json.loads(json.dumps({"Japan":"日本"}).encode("ascii"))
{'Japan': '日本'}

But if you don't bother encoding at all, the loads() still figures out what to do as well when given a str:

>>> json.loads(json.dumps({"Japan":"日本"}))
{'Japan': '日本'}

Python is - as ever - trying to be as helpful as possible in figuring out what you want and doing it, but this is perplexing to people who dig a little deeper, and in spite of loving Python to bits I sympathise with the OP. Whether this kind of 'helpful' behaviour is worth the confusion is a debate that will rage on.

Worth noting that if the next thing to be done with the output is writing to a file, then you can just do:

pathlib.Path("myfile.json").open("w").write(json_data)

Then you don't need it binary because the file is opened in text mode and encoding is done for you.

2 of 3
0

I see this as a 2-step problem

Step 1: Convert json to string my_string = json.dumps(my_json)

Step 2: Convert string to binary string my_binary_string = my_string.encode('utf-8')

Or obviously in one line my_binary_string = json.dumps(my_json).encode('utf-8')

Discussions

python - How to convert binary data to json - Stack Overflow
0 python, from json object (hex) to raw internal binary string More on stackoverflow.com
🌐 stackoverflow.com
Deserialize JSON into a binary file using Python - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... 'UEsDBAoAAAAAALi8T0+jHCkcDAAAAAwAAAAMAAAASUJNX0RhdGEudHh0SGVsbG8gV29ybGQhUEsBAj8ACgAAAAAAuLxPT6McKRwMAAAADAAAAAwAJAAAAAAAAAAgAAAAAAAAAElCTV9EYXRhLnR4dAoAIAAAAAAAAQAYADZQuhPTg9UB2UqCCNOD1QHZSoII04PVAVBLBQYAAAAAAQABAF4AAAA2AAAAAAA=' This text file is a small zip file serialized using JSON. How can I create the original zip file from this sequence of string using Python... More on stackoverflow.com
🌐 stackoverflow.com
October 16, 2019
python - compress the data inside my json file to binary - Stack Overflow
I'd like to convert my json file to a binary format. example(gzip) because I want the data binary. as I searched, I found there is a way to do it with gzip. import json import gzip > def compres... More on stackoverflow.com
🌐 stackoverflow.com
how to serialize arbitrary file types to json string in python - Stack Overflow
I'd like to have one of the fields in my JSON have the value that is a file, encoded as a string. Performance-wise (but also interoperability-wise) what is the best way to encode a file using python? Base64? Binary? More on stackoverflow.com
🌐 stackoverflow.com
🌐
PyPI
pypi.org › project › pbjson
pbjson · PyPI
Packed Binary JSON is available now in the pbjson Python module. That module includes a command line utility to convert between normal JSON files and PBJSON.
      » pip install pbjson
    
Published   Aug 20, 2023
Version   1.19.0
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.3 documentation
February 23, 2026 - fp can now be a binary file. The input encoding should be UTF-8, UTF-16 or UTF-32. Changed in version 3.11: The default parse_int of int() now limits the maximum length of the integer string via the interpreter’s integer string conversion ...
🌐
Python for the Lab
pythonforthelab.com › blog › storing-binary-data-and-serializing
Storing Binary Data and Serializing | Python For The Lab
August 11, 2018 - The limit of JSON is, however, that you have to store data as text files, thus limiting its native capabilities. Fortunately, combining Pickle and base64, you can transform bytes to an ascii string and save it next to easy to read metadata. This article has gone much more in depth regarding how to store data in different formats, but the topic is far from complete. Keep tuned to find more articles regarding how to save data with Python.
🌐
IT trip
en.ittrip.xyz › python
Optimizing Data Handling: Converting JSON to Binary Format | IT trip
November 4, 2023 - By converting JSON to a binary format, you can compress the data, which often results in faster read/write times and reduced storage and bandwidth usage. There are multiple binary formats suitable for different purposes. Some popular binary formats include Protocol Buffers, BSON, and MessagePack. For our Python example, we will use MessagePack, which is an efficient binary serialization format that lets you exchange data among multiple languages like JSON but is faster and smaller.
Find elsewhere
🌐
IT trip
en.ittrip.xyz › python
How to Convert JSON Files to Binary Format for Efficient Storage and Transfer in Python | IT trip
November 25, 2024 - This process uses the standard libraries json and pickle. The pickle module is used to serialize Python objects into binary format. First, we import the pickle module. ... Next, we will read the JSON file using the method described earlier.
🌐
GitHub
github.com › fangq › pybj
GitHub - fangq/pybj: Binary JSON (BJData/UBJSON) Support for Python · GitHub
This is a Python v3.2+ (and 2.7+) Binary JData encoder and decoder based on the Draft-2 specification. ... ## Installing / packaging ## To get from PyPI without root/administrator privilege pip3 install bjdata --user ## To get from PyPI via python python3 -mpip install bjdata ## To only build extension modules in-place (e.g.
Author   fangq
🌐
Hustle Play
hustleplay.wordpress.com › 2010 › 01 › 05 › sending-binary-with-json
Sending Binary with JSON | Hustle Play - WordPress.com
January 5, 2010 - In my work, I used Python on the packaging side and Java on the unpacking side. First, you need to open the file. Since the file is binary, you have to open it with an additional "b" flag.…
🌐
Stack Overflow
stackoverflow.com › questions › 71393092 › compress-the-data-inside-my-json-file-to-binary
python - compress the data inside my json file to binary - Stack Overflow
I'd like to convert my json file to a binary format. example(gzip) because I want the data binary. as I searched, I found there is a way to do it with gzip. import json import gzip > def compres...
🌐
PyMongo
pymongo.readthedocs.io › en › stable › api › bson › index.html
bson – BSON (Binary JSON) Encoding and Decoding - PyMongo 4.16.0 documentation
For uuid.UUID encoding and decoding behavior see https://www.mongodb.com/docs/languages/python/pymongo-driver/current/data-formats/uuid/#universally-unique-ids–uuids-. ... Regex instances and regular expression objects from re.compile() are both saved as BSON regular expressions. BSON regular expressions are decoded as Regex instances. ... The bytes type is encoded as BSON binary with subtype 0. It will be decoded back to bytes. ... BSON (Binary JSON) data.
🌐
Medium
medium.com › @RampantLions › efficiently-storing-and-transmitting-json-compression-and-binary-safety-in-python-a493284fa4c3
Efficiently Storing and Transmitting JSON: Compression and Binary Safety in Python | by Josh Wiechman | Medium
June 6, 2025 - A robust solution is to combine zlib compression, base64 encoding, and Python’s built-in JSON tools. This approach lets you safely transmit or persist compact JSON data — even in binary-unfriendly environments.
🌐
DEV Community
dev.to › devasservice › working-with-csv-json-and-binary-files-in-python-2bge
Working with CSV, JSON, and Binary Files in Python - DEV Community
October 15, 2024 - In this example, we write binary data to a file, which could be part of an image, audio, or any other binary format. In this post, we explored advanced file operations in Python, focusing on working with CSV, JSON, and binary files.
🌐
Johnlekberg
johnlekberg.com › blog › 2020-12-11-stdlib-json.html
Using Python's json module
December 11, 2020 - data = {"a": [1, 2, 3], "b": {"c": "d"}} with open("document.json", "w") as file: json.dump(data, file) with open("document.json", "r") as file: new_data = json.load(file) new_data · {'a': [1, 2, 3], 'b': {'c': 'd'}} new_data == data · True · Here's the Python data that json.dumps supports: Dictionary objects (dict) List objects (list) and tuple objects (tuple). String objects (str). Integer objects (int) and Floating-point objects (float). Boolean objects (True, False) and None objects (None). (json.dumps also supports enum.IntEnum and enum.IntFlag objects.) But what if you need to encode binary data or timestamps?
🌐
PyPI
pypi.org › project › py-ubjson
py-ubjson · PyPI
This is a Python v3.2+ (and 2.7+) Universal Binary JSON encoder/decoder based on the draft-12 specification. # To get from PyPI pip3 install py-ubjson # To only build extension modules inline (e.g.
      » pip install py-ubjson
    
Published   Apr 18, 2020
Version   0.16.1