w3resource

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

Python JSON: Exercise-8 with Solution

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:

[2.0, 3.0]
 

Flowchart:

Flowchart: Check whether a JSON string contains complex object 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 check whether an instance is complex or not.
Next: Write a Python program to access only unique key value of a Python object.

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)