w3resource

Python JSON: Check whether an instance is complex or not


7. 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:

Flowchart: Check whether an instance is complex or not.

For more Practice: Solve these Related Problems:

  • Write a Python program to determine if a given variable is of type complex using isinstance().
  • Write a Python program to check a list of mixed-type values and return those that are complex numbers.
  • Write a Python program to implement a function that tests if the input is a complex number and returns True or False.
  • Write a Python program to iterate over a set of variables and print only those that are instances of the complex type.

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.



Follow us on Facebook and Twitter for latest update.