Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I was trying to check if objects were JSON serializable or not because I had a dictionary that had a bunch of things and at this point its just easier to loop through its keys and find if they are JSON serializable and remove them. Something like (though this checks if its 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 a way that the if statement instead check for JSON serializable objects and deletes them from the dictionary in a similar way to above?

like image 997
Charlie Parker Avatar asked Feb 03 '17 21:02

Charlie Parker


People also ask

How do I know if JSON is serialized?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JSchema) method with the JSON Schema. To get validation error messages use the IsValid(JToken, JSchema, IList<String> ) or Validate(JToken, JSchema, SchemaValidationEventHandler) overloads.

How do you serialize a JSON in Python?

The json module exposes two methods for serializing Python objects into JSON format. dump() will write Python data to a file-like object. We use this when we want to serialize our Python data to an external JSON file. dumps() will write Python data to a string in JSON format.

How do I make my Python object JSON serializable?

Use toJSON() Method to make class JSON serializable So we don't need to write custom JSONEncoder. This new toJSON() serializer method will return the JSON representation of the Object. i.e., It will convert custom Python Object to JSON string.

Is JSON serializable Python?

Serialization is the process of encoding the from naive data type to JSON format. The Python module json converts a Python dictionary object into JSON object, and list and tuple are converted into JSON array, and int and float converted as JSON number, None converted as JSON null.


2 Answers

@shx2's answer is good enough, but it's better to specify which exceptions you're catching.

def is_jsonable(x):     try:         json.dumps(x)         return True     except (TypeError, OverflowError):         return False 

OverflowError is thrown when x contains a number which is too large for JSON to encode. A related answer can be found here.

like image 108
R. Yang Avatar answered Sep 19 '22 02:09

R. Yang


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) 
like image 38
shx2 Avatar answered Sep 17 '22 02:09

shx2