How can I create the empty json object?
Simply:
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
loads()
takes a json formatted string and turns it into a Python object like dict or list. In your code, you're passing dict()
as default value if mydata
doesn't exist in request.POST
, while it should be a string, like "{}"
. So you can write -
json_data = json.loads(request.POST.get('mydata', "{}"))
Also remember, the value of request.POST['mydata']
must be JSON formatted, or else you'll get the same error.