How can I create an empty json object in python

I have this code

json.loads(request.POST.get('mydata',dict())) 

But I get this error

 No JSON object could be decoded 

I just want that if I don't have mydata in POST, I don't get this error

+8
json python
source share
2 answers

Just:

 json.loads(request.POST.get('mydata', '{}')) 

Or:

 data = json.loads(request.POST['mydata']) if 'mydata' in request.POST else {} 

Or:

 if 'mydata' in request.POST: data = json.loads(request.POST['mydata']) else: data = {} # or data = None 
+16
source share

loads() takes a formatted json string and turns it into a Python object such as dict or list. In your code, you pass dict() as the default value if mydata does not exist in request.POST , while it should be a string, for example "{}" . So you can write -

 json_data = json.loads(request.POST.get('mydata', "{}")) 

Also remember that the request.POST['mydata'] value must be JSON formatted, otherwise you will get the same error.

+1
source share

All Articles