aamir23 aamir23 - 1 year ago 153
JSON Question

Load JSON file in current distribution of a python package using pkg_resources

I am building a package that has the following directory structure -


I am trying to load config.json into pp_helpers.py using pkg_resources, as mentioned on other similar questions. I am sure the file exists because -

>>print resource_exists('terraai_preprocessing.preprocessing', 'config.json')

I have tried using the following but ended up with errors, -

>>with open(resource_filename('terraai_preprocessing.preprocessing', 'config.json'),'r') as f:
config = json.load(f)
ValueError: No JSON object could be decoded

>>config = json.loads(resource_filename('terraai_preprocessing.preprocessing', 'config.json'))
ValueError: No JSON object could be decoded

>>config = json.loads(resource_stream('terraai_preprocessing.preprocessing', 'config.json'))
enter code here

>>config = json.loads(resource_string('terraai_preprocessing.preprocessing', 'config.json'))
ValueError: No JSON object could be decoded

What am I doing wrong

Answer Source

Python could not find the file as the function resource_filename() returns the address with \\ as separators. By replacing \\ with / it was able to locate the file.

So I used the following code -

>> file_location = resource_filename('terraai_preprocessing.preprocessing','config.json').replace('\\',"/")

>> with open(file_location,'r') as f:
      config = json.load(f)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download