Is there an easy way to check if a JSON object is serializable in python?

I tried to check if the JSON objects were serializable or not, because I had a dictionary that had a bunch of things, and at this point it is easiest to scroll through my keys and find out if they are JSON-serializable and delete them. Something like (although this checks to see if there is a function):

def remove_functions_from_dict(arg_dict): ''' Removes functions from dictionary and returns modified dictionary ''' keys_to_delete = [] for key,value in arg_dict.items(): if hasattr(value, '__call__'): keys_to_delete.append(key) for key in keys_to_delete: del arg_dict[key] return arg_dict 

is there any way that the if statement checks for serializable JSON objects and removes them from the dictionary similarly above?

+5
source share
1 answer

It’s easier to ask forgiveness than permission.

 import json def is_jsonable(x): try: json.dumps(x) return True except: return False 

Then in your code:

 for key,value in arg_dict.items(): if not is_jsonable(value): keys_to_delete.append(key) 
+8
source

Source: https://habr.com/ru/post/1263803/


All Articles