Python JSON: Check whether an instance is complex or not
Python JSON: Exercise-7 with Solution
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/python-json-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics