Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare "null" json values in python

Tags:

python

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
like image 487
codec Avatar asked Dec 03 '22 15:12

codec


1 Answers

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

like image 140
Carlos Mermingas Avatar answered Dec 22 '22 11:12

Carlos Mermingas