我有一個需要配置文件的Python測試腳本。預計配置文件將採用JSON格式。有沒有辦法確定文件是YAML格式還是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)
現在,有一個Python模塊我在互聯網上被稱爲isityaml可用於測試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加載。 (我不確定它是否是一個確切的超集 - 我認爲以前的版本不是。) – user2357112
難道你只需要YAML文件有一個擴展名和JSON文件有不同的擴展名? – user2357112
user2357112,有兩個問題。 1)某些用戶可能會在沒有.yml或.json後綴的情況下爲其配置文件命名,所以我不能通過其配置文件中的後綴 2)僅僅因爲文件具有.yml後綴並不一定意味着該文件是YAML格式。 – SQA777