Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file is json loadable

Tags:

python

json

I have two types of txt files, one which is saved in some arbitrary format on the form

Header
key1 value1
key2 value2

and the other file formart is a simple json dump stored as

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

From a dialog window, the user can load either of these two files, but my loader need to be able to distinguish between type1 and type2 and send the file to the correct load routine.

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

The easiest way I can think of is to use a try/except block as

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

but I do not like this approach since there is like a 50/50 risk of fail in the try/except block, and as far as I know try/except is slow if you fail.

So is there a simpler and more convenient way of checking if its json-format or not?

like image 332
pathoren Avatar asked Oct 02 '22 18:10

pathoren


1 Answers

You can do something like this:

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>
like image 184
Vor Avatar answered Oct 05 '22 12:10

Vor