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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With