Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python check if json.dumps is possible

Tags:

python

json

is it possible to check if a value is able to be "json.dumps"d like json.dumping.possible(code) with a boolean output? I would be thankful for help

like image 846
Hans Avatar asked May 18 '14 20:05

Hans


People also ask

How do you check if a key exists in a JSON in Python?

Check if the key exists or not in JSON if it is present directly to access its value instead of iterating the entire JSON. Note: We used json. loads() method to convert JSON encoded data into a Python dictionary. After turning JSON data into a dictionary, we can check if a key exists or not.

Does JSON dumps return a string?

dumps() takes in a json object and returns a string.

What is the difference between JSON dump and JSON dumps?

dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.


1 Answers

There is no way to check if an object is serializable to a json format. However, you can (even if it is not really EAFP compliant) try and if it fails go for a fallback process:

try:
    json.dumps(my_object)
except TypeError:
    print("Unable to serialize the object")

A way to be sure would be to implement your own JSONEncoder if you are entirely sure of the data processed.

like image 83
Maxime Lorant Avatar answered Sep 18 '22 02:09

Maxime Lorant