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:
Complex_object: (4+5j) Without complex object: {'real': 4, 'img': 3}
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 Python skills with w3resource's quiz
Python: Tips of the Day
Python: Unknown Arguments Using *arguments
If your function can take in any number of arguments then add a * in front of the parameter name:
def myfunc(*arguments): for a in arguments: print a myfunc(a) myfunc(a,b) myfunc(a,b,c)
- New Content published on w3resource :
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework