Skip to main content
 首页 » 编程设计

python之检查文件是否可加载 json

2024年11月01日9落叶无声

我有两种类型的 txt 文件,一种以某种任意格式保存在表单上

Header 
key1 value1 
key2 value2 

另一种文件格式是一个简单的 json 转储,存储为

with open(filename,"w") as outfile: 
    json.dump(json_data,outfile) 

从对话窗口中,用户可以加载这两个文件中的任何一个,但我的加载程序需要能够区分 type1 和 type2 并将文件发送到正确的加载例程。

#Pseudocode 
def load(filename): 
    if filename is json-loadable: 
        json_loader(filename) 
    else: 
        other_loader(filename) 

我能想到的最简单的方法是使用 try/except block 作为

def load(filename): 
    try: 
        data = json.load(open(filename)) 
        process_data(data) 
    except: 
        other_loader(filename) 

但我不喜欢这种方法,因为在 try/except block 中有大约 50/50 的失败风险,据我所知,如果失败,try/except 会很慢。

那么有没有更简单方便的方法来判断是否是json格式呢?

请您参考如下方法:

你可以这样做:

def convert(tup):                                                                
    """                                                                             
    Convert to python dict.                                                         
    """                                                                             
    try:                                                                            
        tup_json = json.loads(tup)                                                  
        return tup_json                                                             
    except ValueError, error:  # includes JSONDecodeError                           
        logger.error(error)                                                            
        return None  
 
 
converted = convert(<string_taht_neeeds_to_be_converted_to_json>): 
if converted:     
    <do_your_logic> 
else: 
    <if_string_is_not_converteble>