Python JSON: Check whether an instance is complex or not
Write a Python program to check whether an instance is complex or not.
Sample Solution:-
Python Code:
import json
def encode_complex(object):
# check using isinstance method
if isinstance(object, complex):
return [object.real, object.imag]
# raised error if object is not complex
raise TypeError(repr(object) + " is not JSON serialized")
complex_obj = json.dumps(2 + 3j, default=encode_complex)
print(complex_obj)
Output:
[2.0, 3.0]
Flowchart:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to create a new JSON file from an existing JSON file.
Next: Write a Python program to check whether a JSON string contains complex object or not.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics