Using Python 3.5.1, I pulled in a text file where each line is in JSON form: {"a":"windows", "b":"stairs"...}
import json
path = 'folder/data.txt'
records=[json.loads(line) for line in open(path,'rb')]
But I received the error:
the JSON object must be str, not 'bytes'
I have no problem printing the first line of file, so I am reassured that the file path is correct.
Open the file in text mode, not binary mode (possibly explicitly passing encoding='utf-8'
to override the system default, since JSON is usually stored as UTF-8). The json
module only takes str
input; reading from a file opened in binary mode returns bytes
objects:
# Using with statement just for good form; in this case it would work the
# same on CPython, but on other interpreters or different CPython use cases,
# it's easy to screw something up; use with statements all the time to build good habits
with open(path, encoding='utf-8') as f:
records=[json.loads(line) for line in f]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With