w3resource

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:

Flowchart: Check whether an instance is complex or not.

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)