简体   繁体   中英

Best way to manipulate variables inside a JSON config file in Python3

I want to have a JSON config file where I can reference values ​​internally. For example, consider this JSON config file at bellow:

{
  "hdfs-base":"/user/SOME_HDFS_USER/SOME_PROJECT"
 ,"incoming-path":"$hdfs-base/incoming"
 ,"processing-path":"$hdfs-base/processing"
 ,"processed-path":"$hdfs-base/processed"
}

The main idea is to leverage values already stored in json object. In this case, replacing '$hdfs-base' to 'hdfs-base' attribute's value. Do you know something that do that already? I don't wanna use ConfigParser module because I want to use JSON.

Thanks!

Loop over your values, and substitute the keys if there's a match:

import json

js = open('input.json').read()
data = json.loads(js)

for k, v in data.items():
  for key in data.keys():
    if key in v:
      data[k] = v.replace("$" + key, data[key])

BEFORE

hdfs-base /user/SOME_HDFS_USER/SOME_PROJECT
incoming-path $hdfs-base/incoming
processing-path $hdfs-base/processing
processed-path $hdfs-base/processed

AFTER

hdfs-base /user/SOME_HDFS_USER/SOME_PROJECT
incoming-path /user/SOME_HDFS_USER/SOME_PROJECT/incoming
processing-path /user/SOME_HDFS_USER/SOME_PROJECT/processing
processed-path /user/SOME_HDFS_USER/SOME_PROJECT/processed

REPL: https://repl.it/repls/NumbMammothTelephone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM