1

First software job and l inherited a codebase with heavy JSON usage. I'm trying to use Python to load a text file from accessing a JSON element. My relative path understanding is limited but l'm able to load python modules in the same sub directory (not using JSON though). This data file is in the same folder.

I parse and store data within the JSON element here:

with open(cfg) as fp:
    edict = json.load(fp)
if edict["dtype"] == "custom" :
    data = edict["dtype"]["custom"]["datapath"]

Relevant section of JSON file:

{
"dtype" : {
    "custom" : {
        "datapath" : "DataPipeLine/example_data.txt",
        "type" : "T",
        "X" : "encoder",
        "Y" : "encoder"
    }
  }
}

I get an error from passing the data variable into a function later in the program:

UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it has been declared.

1 Answer 1

1

There are too many errors in your code

I assumed your project directory like this

.
├── DataPipeLine
│   └── example_data.txt
├── cfg.json
└── main.py

There is the right code example

import json
from pathlib import Path

# Get current directory
CUR_DIR = Path(__file__).parent.absolute()


def load_data(path: Path):
    print(path.read_text())


# cfg file path
cfg = CUR_DIR / 'cfg.json'
with cfg.open() as fp:
    edict = json.load(fp)

    # Check there is custom node or not
    if edict["dtype"]["custom"]:
        # Generate your datapath
        data_path = CUR_DIR / edict["dtype"]["custom"]["datapath"]
        load_data(data_path)

If my answer solved your problem please accept it as the right answer.

Sign up to request clarification or add additional context in comments.

2 Comments

Mr. He, cfg.json and main.py are in the same folder as example_data.txt. I'm not sure it matters with your answer. I'll check it out at work.
@Artificial_Spark If in this case, just simply change data_path = CUR_DIR / '..' / edict["dtype"]["custom"]["datapath"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.