2016-05-03 29 views
0

我的一個的API給一個JSON輸出如何比較「空」 JSON在Python值

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

我試圖通過以下方式比較該空值,但是沒有一個工作

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

什麼是比較空值的正確方法?

全碼:

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

回答

5

解決方案:

使用None

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

原來的問題:

這種分配看起來LIK ËJSON,但它不是(這是一個本地的Python陣列本地 Python字典內):

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

這不會起作用,因爲null不Python中存在。

JSON數據會進來的字符串:

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

而且你必須使用解析它的​​:

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

注意如何null成爲None

+0

好,我想這'如果(student ['id']不是None):print(「not null」)'但它不起作用。不知道爲什麼。 – aaj

+0

你會得到什麼錯誤?你的範圍中的'學生'是什麼?在這裏if語句之前粘貼更多的代碼。 –

+0

添加了有問題的完整代碼。 – aaj