My JSON response has this structure:
{
"hpsId": 10012,
"powerPlant": {
"name": "xx",
"id": xx,
"spotlessId": xx,
"regionId": xx,
"priceArea": x,
"timeSeries": [
{
"name": "ts.plan.sum",
"dtssId": "",
"tsv": {
"pfx": false,
"data": [
[
1724846400,
83
],
{
"name": "ts.max_prod.sum",
"dtssId": "",
"tsv": {
"pfx": false,
"data": [
[
1724846400,
null
],
....
I want to check if the FIRST data element is not null (now it is 83) and I want to return i.e. 1 of it is not null and 0 if it is null using somewhat this kind of method (pseudo code ish):
def get_bids_for_pp(d):
for x in d
for unit in x["data[0]"]:
if unit["data[0[1]]"] !=None
return 1
else:
return 0
I understand I have to use None (not null) for Python, but is the logic in the method correct?
3
Answers
You could for example check if the second element is not null for all datas inside "data" array inside "tsv" for all "timeSeries".
Here’s a Python function that checks if the first data element in the JSON response is not None and returns 1 or 0 accordingly:
Tweaking @KamilCuk’s answer to fit your proposed logic:
This will return
True
if any of the time series data entries is not None. I think this is what you want based on your pseudocode. If you want instead to returnTrue
if all are valid (and none arenull
), you’d useall
instead ofany
.What this does is use a generator expression to filter out the second data element. It does the
for
loop all in one expression. It passes each element to the conditional expressionunit[1] is not None
and generates a list of results. (Actually, internally, it passes a function that generates the list of results on-the-fly, not the list itself, but the logic is the same.) It passes this toany
, which will returnTrue
if any of the elements it is passed areTrue
. So you get an answer in one fell swoop.You should always use
is not None
and not!= None
as you discovered, because None is such a special value.This code makes the assumption that
data
is a list of lists and that you want to scan the second element of all the lists, returningTrue
if any is notnull
(i.e. if not all of them arenull
).If you really want to return
1
or0
(not recommended; better to useTrue
andFalse
), use