如何从 Pycharm 中的 json 文件自动生成 Getters
How to autogenerate Getters from a json file in Pycharm
我有一个非常大的 config.json
文件,我正在尝试从 pycharm IDE
.
中读取并生成吸气剂
样本 config.json
看起来像这样(. . .
表示很多相似的项目):
{
"key1" : "value1",
"key2" : "value2",
.
.
.
"key1000" : value1000
}
我的 python ConfigRead.py
class 看起来像这样:
import json
class ConfigRead(object):
def __init__(self, file_path):
json_content = open(file_path).read()
self.jsonData = json.loads(json_content)
def get_config(self):
return self.jsonData
def get_key1(self):
return self.jsonData["key1"]
现在输入 1000
吸气剂是我不想尝试的事情。
Eclipse
具有从配置文件自动生成的方法。我已经迁移到 PyCharm
,但我无法弄明白。
任何线索都会对简化此过程有所帮助。谢谢。
如果您在 python
中认为这是一种糟糕的方法,我也乐于接受任何建议。如果我的设计可以简化并使事情更易于管理,我愿意改变我的设计。
您是否考虑过实施 __getitem__
? __getitem__
是让您使用 []
运算符的神奇方法,我认为这是一种更可持续的方法,因为它不需要您更改源代码每次配置文件更改时的代码。我不知道您的具体用例是什么,但类似于:
class ConfigRead(object):
def __init__(self, file_path):
json_content = open(file_path).read()
self.jsonData = json.loads(json_content)
def __getitem__(self, key):
return self.jsonData[key]
会让你写这样的东西:
config = ConfigRead("path/to/file")
name = config['key1']
或者,如果您不想对配置数据进行任何额外处理,您可以直接使用 JSON 数据,如下所示:
def read_config(file_path):
with open(file_path) as config_file:
return json.load(config_file)
config = read_config("path/to/file")
name = config['key1']
我有一个非常大的 config.json
文件,我正在尝试从 pycharm IDE
.
样本 config.json
看起来像这样(. . .
表示很多相似的项目):
{
"key1" : "value1",
"key2" : "value2",
.
.
.
"key1000" : value1000
}
我的 python ConfigRead.py
class 看起来像这样:
import json
class ConfigRead(object):
def __init__(self, file_path):
json_content = open(file_path).read()
self.jsonData = json.loads(json_content)
def get_config(self):
return self.jsonData
def get_key1(self):
return self.jsonData["key1"]
现在输入 1000
吸气剂是我不想尝试的事情。
Eclipse
具有从配置文件自动生成的方法。我已经迁移到 PyCharm
,但我无法弄明白。
任何线索都会对简化此过程有所帮助。谢谢。
如果您在 python
中认为这是一种糟糕的方法,我也乐于接受任何建议。如果我的设计可以简化并使事情更易于管理,我愿意改变我的设计。
您是否考虑过实施 __getitem__
? __getitem__
是让您使用 []
运算符的神奇方法,我认为这是一种更可持续的方法,因为它不需要您更改源代码每次配置文件更改时的代码。我不知道您的具体用例是什么,但类似于:
class ConfigRead(object):
def __init__(self, file_path):
json_content = open(file_path).read()
self.jsonData = json.loads(json_content)
def __getitem__(self, key):
return self.jsonData[key]
会让你写这样的东西:
config = ConfigRead("path/to/file")
name = config['key1']
或者,如果您不想对配置数据进行任何额外处理,您可以直接使用 JSON 数据,如下所示:
def read_config(file_path):
with open(file_path) as config_file:
return json.load(config_file)
config = read_config("path/to/file")
name = config['key1']