1

this is my json may be thousands of record data we request in django rest framework.

{
 "a":1,
 "b":2,
 "c":3,
 .....
}

if request.data['a'] == '':
   return JsonResponse({'error':1})
elif request.data['b'] == '':
   return JsonResponse({'error':1})
elif .....
   .......
else:
   ......

I want to check data is not blank like above if... else. we can add if else condition but this is not possible to check all data from if else Please suggest me what is the best way to check this line of code in python.

Sandeep
  • 619
  • 1
  • 7
  • 18
  • Did you check any question like [this](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops)? – Sachin Jun 26 '19 at 05:33
  • user [DRF-Serializer](https://www.django-rest-framework.org/api-guide/serializers/) and provide a [**`allow_null=False`**](https://www.django-rest-framework.org/api-guide/fields/#allow_null) – JPG Jun 26 '19 at 06:00

4 Answers4

2

If you are using json module for parsing the json response text using json.loads, then you can directly access it like a dict as following.

import json
json_data = json.loads(json_text)

for mykey in json_data:
    if json_data[mykey] = "":
        return JsonResponse({'error':1})
    else:
        pass
najeem
  • 1,841
  • 13
  • 29
1

you can do a check using for loop

for i in your_dict.keys():
    if your_dict[i] == '':
       do something
    else:
       do other thing
Exprator
  • 26,992
  • 6
  • 47
  • 59
1

You can use data.items() to get key and value AND then you can process according to your demands:-

import json
data = { "a":1, "b":2, "c":3  }
for key,value in data.items():  # Here you will get key and value.
    if value == '':
        return JsonResponse({'error':1})
    else:
        pass 
heemayl
  • 39,294
  • 7
  • 70
  • 76
Rahul charan
  • 765
  • 7
  • 15
0

Here's a simple solution

data = {
    "a": 1,
    "b": 2,
    "c": "",
    "d": ""
}

for key in data:
    if bool(data[key]):
        pass
    else:
        return JsonResponse({"error":1})
Maulik Patel
  • 572
  • 5
  • 10