w3resource

Python JSON: Check whether a JSON string contains complex object or not


8. Check Whether a JSON String Contains a Complex Object

Write a Python program to check whether a JSON string contains complex object or not.

Sample Solution:-

Python Code:

import json
def is_complex_num(objct):
    if '__complex__' in objct:
        return complex(objct['real'], objct['img'])
    return objct

complex_object =json.loads('{"__complex__": true, "real": 4, "img": 5}', object_hook = is_complex_num)
simple_object =json.loads('{"real": 4, "img": 3}', object_hook = is_complex_num)
print("Complex_object: ",complex_object)
print("Without complex object: ",simple_object)

Output:

Complex_object:  (4+5j)
Without complex object:  {'real': 4, 'img': 3}

Flowchart:

Flowchart: Check whether a JSON string contains complex object or not.

For more Practice: Solve these Related Problems:

  • Write a Python program to parse a JSON string and detect if any of its values represent a complex number (using a custom marker).
  • Write a Python program to check if a JSON string, when converted to a Python object, contains any complex objects by scanning its values.
  • Write a Python program to implement a function that validates whether a JSON string contains non-standard data types such as complex numbers.
  • Write a Python program to use exception handling during JSON decoding to determine if the string includes complex objects.

Go to:


Previous: Write a Python program to check whether an instance is complex or not.
Next: Write a Python program to access only unique key value of a Python object.

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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.