我有两种类型的txt文件,一种以任意格式保存在表单上
Header
key1 value1
key2 value2
Run Code Online (Sandbox Code Playgroud)
另一个文件格式是一个简单的 json 转储,存储为
with open(filename,"w") as outfile:
json.dump(json_data,outfile)
Run Code Online (Sandbox Code Playgroud)
从对话窗口,用户可以加载这两个文件中的任何一个,但我的加载器需要能够区分 type1 和 type2 并将文件发送到正确的加载例程。
#Pseudocode
def load(filename):
if filename is json-loadable:
json_loader(filename)
else:
other_loader(filename)
Run Code Online (Sandbox Code Playgroud)
我能想到的最简单的方法是使用 try/except 块作为
def load(filename):
try:
data = json.load(open(filename))
process_data(data)
except:
other_loader(filename)
Run Code Online (Sandbox Code Playgroud)
但我不喜欢这种方法,因为 try/except 块中有 50/50 的失败风险,据我所知,如果失败,try/except 会很慢。
那么有没有更简单、更方便的方法来检查它是否是 json 格式?