im using fastapi and python and need to check in dictionary if value is null.
i have a json like this:
{
"id": null,
"first_name": null,
"last_name": null,
"email": null,
"user_id": null,
"active": null
},
using a query to DB. my dictionary sting is
user = {"id": n['id'], "first_name": n['first_name'], "last_name": n['last_name'],
"email": n['a_email'], "user_id": n['user_id'], "active": n['active']}
this values "active": null is empty in the table. How i can use if-else in python to check, if unique_id is null i need to write in my json only {null}
but if "unique_id": inc['a_unique_id'] have a value for example, 1, i need to get all info from this row:
{
"id": 1 ,
"first_name": "username",
"last_name": "userlastname",
"email": ""email@email.com,
"user_id": userlogin,
"active": 0
},
final json i need to get should looks like this
--for row with info ---
{
"id": 1 ,
"first_name": "username",
"last_name": "userlastname",
"email": ""email@email.com,
"user_id": userlogin,
"active": 0
},
for row with null values
{null}
i tried something like this
if n['id'] == "null":
user = {"user": "NULL"}
else:
user= {"id": n['id'], "first_name": n['first_name'], "last_name": n['last_name'],
"email": n['email'], "user_id": n['user_id'], "active": n['active']}
but this dont work like i need
Python's None
is equivalent to JSON's null
.
So what you should do is the following:
if n['id'] is None:
user = None
else:
user= {"id": n['id'],
"first_name": n['first_name'],
"last_name": n['last_name'],
"email": n['email'],
"user_id": n['user_id'],
"active": n['active']}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.