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?
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.
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.
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.
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.
@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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With