7

One of my APIs give a json output

{"student":{"id": null}}

I tried comparing this null value in the following ways but none is working

 if(student['id'] == "null")
 if(student['id'] == None)
 if(student['id'] == null)

What is the correct way to compare null values?

Full code:

 students = [{"id":null},{"id":1},{"id":3}]   
 for student in students:
     if(student['id'] is not None):
         print("found student" + str(student['id']))
         break

2 Answers 2

21

Solution:

Use None

>>> import json
>>> b = json.loads('{"student":{"id": null}}')
>>> b['student']['id'] is None
True

Original Problem:

This assignment looks like JSON but it's not (it's a native Python array with native Python dictionaries inside):

students = [{"id":null},{"id":1},{"id":3}] 

This won't work because null does not exist in Python.

JSON data would come in a string:

students = '[{"id":null},{"id":1},{"id":3}]'

And you have to parse it using the json module:

>>> import json
>>> parsed_students = json.loads(students)
>>> print(parsed_students)
[{'id': None}, {'id': 1}, {'id': 3}]

Notice how null became None

Sign up to request clarification or add additional context in comments.

9 Comments

well I tried this if(student['id'] is not None): print("not null") but it's not working. Not sure why.
What error do you get? What is 'student' in your scope? Paste a bit more code before that if statement here.
I see. 'null' does not exist in Python. Your first line is not JSON, it's a Python array. Enclose it in single quote marks and then parse it using json.loads (see the second line in my answer above)
well this array is stored in a variable and is an output of some other function. How can I enclose it in ' ' ?
Can I use json.loads(student_array_element) eg: json.loads(student)` inside the for loop before the if statement
|
1

Working code

Most of the case in python we can't compare abc = 'null' for json null values so we should use some hack which json.loads() gives use i.e json.loads() provide None value for json null values. So use as below;

 #Check for null value as wel as json null value 
        if existing_tags_str and json.loads(existing_tags_str) is not None:
            print("dosomething")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.