Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting Json Value from path python

Tags:

python

json

I have a sample Json which contains key as fileName and value as filepath. For example:

{
  "sqlFiles":{
    "sqlQueryPath": "tmp/r/test.sql"
  },
  "csvFiles": {
    "firstSampleInput": "tmp/c/sample.csv",
    "secondSampleInput": "tmp/c/sample1.csv"
  }
}

and I have a function which takes key as input and return value as output. Something like this:

def readFilePath(key):
    with open('filePaths.json', 'r') as f:
        config = json.load(f)
        value = config[key]
        return value

If the key is available as a root element then my functions totally works but if the key is available in nested format just like it is available in the json then my function will fail.

I will call the function with the json path something like this:

readFilePath("sqlFiles.sqlQueryPath")

What changes to be made in the function that it parse the path in the format config["sqlFiles"]["sqlQueryPath"]

like image 644
talkdatatome Avatar asked Mar 26 '26 11:03

talkdatatome


1 Answers

This is one approach. Using a simple iteration.

Demo:

key = "sqlFiles.sqlQueryPath"

def readFilePath(key):
    config = {
          "sqlFiles":{
            "sqlQueryPath": "tmp/r/test.sql"
          },
          "csvFiles": {
            "firstSampleInput": "tmp/c/sample.csv",
            "secondSampleInput": "tmp/c/sample1.csv"
          }
        }

    for i in key.split("."):
        if i in config:
            config = config[i]
        else:
            return None


    return config

print(readFilePath(key))
like image 159
Rakesh Avatar answered Mar 29 '26 01:03

Rakesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!