24

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 don't have mydata in POST, then I don't get that error.

2 Answers 2

32

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
Sign up to request clarification or add additional context in comments.

1 Comment

One snafu here that often catches people is the empty string. If mydata is empty, then this will fail and the default argument in the get won't save you.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.