【发布时间】:2017-11-04 10:51:41
【问题描述】:
我有一个需要配置文件的 Python 测试脚本。配置文件应为 JSON 格式。
但是我的测试脚本的一些用户不喜欢 JSON 格式,因为它不可读。
所以我更改了我的测试脚本,使其需要 YAML 格式的配置文件,然后将 YAML 文件转换为 JSON 文件。
我希望加载配置文件的函数同时处理 JSON 和 YAML。如果配置文件是 JSON 或 YAML,yaml 或 json 模块中是否有方法可以给我一个布尔响应?
我现在的解决方法是使用两个 try/except 子句:
import os
import json
import yaml
# This is the configuration file - my script gets it from argparser but in
# this example, let's just say it is some file that I don't know what the format
# is
config_file = "some_config_file"
in_fh = open(config_file, "r")
config_dict = dict()
valid_json = True
valid_yaml = True
try:
config_dict = json.load(in_fh)
except:
print "Error trying to load the config file in JSON format"
valid_json = False
try:
config_dict = yaml.load(in_fh)
except:
print "Error trying to load the config file in YAML format"
valid_yaml = False
in_fh.close()
if not valid_yaml and not valid_json:
print "The config file is neither JSON or YAML"
sys.exit(1)
现在,我在 Internet 上找到了一个名为 isityaml 的 Python 模块,可用于测试 YAML。但我不想安装另一个包,因为我必须在多个测试主机上安装它。
json 和 yaml 模块是否有一种方法可以返回一个布尔值来测试它们各自的格式?
config_file = "sample_config_file"
# I would like some method like this
if json.is_json(in_fh):
config_dict = json.load(in_fh)
【问题讨论】:
-
YAML 不是 JSON 的超集吗?您应该能够无条件地将文件加载为 YAML。 (我不确定它是否是一个精确的超集——我认为以前的版本不是。)
-
你不能只要求 YAML 文件有一个扩展名而 JSON 文件有一个不同的扩展名吗?
-
user2357112,有两个问题。 1) 一些用户可能会在没有 .yml 或 .json 后缀的情况下命名他们的配置文件,所以我不能在他们的配置文件中使用后缀 2) 仅仅因为文件具有 .yml 后缀并不一定意味着该文件是YAML 格式。
-
user2357112,我测试了使用 yaml.load 加载 json 文件和使用 json.load 加载 yaml 文件,并且都断言(这是在 try/except 块之外)
-
不要使用 PyYAML 的
load(),在不受控制的数据上,它是不安全的(即你可以擦除你的光盘)。