Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON object must be str, not 'bytes'

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.

like image 410
Greg Avatar asked Feb 04 '16 04:02

Greg


1 Answers

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]
like image 50
ShadowRanger Avatar answered Oct 04 '22 15:10

ShadowRanger