简体   繁体   English

在 Python3 中操作 JSON 配置文件中的变量的最佳方法

[英]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.我想要一个 JSON 配置文件,我可以在其中在内部引用值。 For example, consider this JSON config file at bellow:例如,考虑下面的这个 JSON 配置文件:

{
  "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.主要思想是利用已经存储在json对象中的值。 In this case, replacing '$hdfs-base' to 'hdfs-base' attribute's value.在这种情况下,将 '$hdfs-base' 替换为 'hdfs-base' 属性的值。 Do you know something that do that already?你知道什么已经做到了吗? I don't wanna use ConfigParser module because I want to use JSON.我不想使用ConfigParser模块,因为我想使用 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 REPL: https : //repl.it/repls/NumbMammothTelephone

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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