Search code examples
pythonjsonpython-3.xpkg-resources

How to load json from resource_stream in python 3


I'm trying to use to use resource_stream from pkg_resources in conjunction with json.load and am having problem in python 3 that were not present in python 2.

When I try to run the following command, I get the error:

loaded_json = json.load(resource_stream(__name__, 'path/to/foo.json'))

>> TypeError: the JSON object must be str, not 'bytes'

Solution

  • It looks like in Python 3, json.load no longer supports reading from a bytestream, you'll have to decode it before parsing it:

    json_string = resource_stream(__name__, 'path/to/foo.json').read().decode()
    loaded_json = json.loads(json_string)