user2330497
user2330497

Reputation: 419

How can I create the empty json object?

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.

Upvotes: 24

Views: 95592

Answers (2)

Bibhas Debnath
Bibhas Debnath

Reputation: 14939

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.

Upvotes: 1

defuz
defuz

Reputation: 27611

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

Upvotes: 32

Related Questions