Aug-30-2018, 04:30 PM
This took me a while to figure out, woludn't have 15 years ago, but the result is quite simple:
I wanted to store pathlib objects in a json file, so that I can use as objects when reading the file back in.
Here's the solution:
I wanted to store pathlib objects in a json file, so that I can use as objects when reading the file back in.
- The script below will create a 'data' directory one level higher than current directory, or use existing 'data' directory if already there.
- within that directory, will create a json directory which will contain two differently named, but each with identical contents, which is a dictionary containing two pathlib paths.
- load that json file back into a new dictionary (with json load)
- use one of the pathlib links to read the other json file as plain text
- Print the text
Here's the solution:
import json from pathlib import Path import os def json_writer(): os.chdir(os.path.dirname(__file__)) homepath = Path('.') datapath = homepath / 'data' datapath.mkdir(exist_ok=True) jsonpath = datapath / 'json' jsonpath.mkdir(exist_ok=True) file1 = jsonpath / 'TestPath1.json' file2 = jsonpath / 'TestPath2.json' pathdict = { 'path1': str(file2), 'path2': str(file1), } with file1.open('w') as fp: json.dump(pathdict, fp) with file2.open('w') as fp: json.dump(pathdict, fp) newdict = {} with file2.open() as fp: newdict = json.load(fp) filename = Path(newdict['path1']) with filename.open() as fp: text = fp.read() print(text) if __name__ == '__main__': json_writer()And the results are:
Output:{"path1": "data/json/TestPath2.json", "path2": "data/json/TestPath1.json"}