简体   繁体   中英

How to parse json in my view from a requests post

I have the following requests code:

>>> data
{'AmountInUSD': '40', 'CreditCardLastFourDigits': '1111'}
>>> r=requests.post('http://localhost:8000/api/v1.0/balance/deposit/', data=data)

Here is how I am trying to parse the json, but I keep getting an ValueError: No JSON object could be decoded :

def deposit(request):
    print '***', request.POST
    print '>>>', request.raw_post_data
    print '###', request.body
    json.loads(request.raw_post_data)

And it prints:

*** <QueryDict: {u'AmountInUSD': [u'40'], u'CreditCardLastFourDigits': [u'1111']}>
>>> AmountInUSD=40&CreditCardLastFourDigits=1111
### AmountInUSD=40&CreditCardLastFourDigits=1111

How should I be doing this instead?

In your code, the incoming request has already been converted to a QueryDict , it is not a json string which is why json.loads cannot do anything with it.

The reason its a QueryDict is because you passed the dictionary to requests.post and it correctly posted it as part of the request body as form-encoded data.

As its a QueryDict object, you can access it just like a Python dictionary:

request.POST.get('AmountInUSD')
request.POST.get('CreditCardLastFourDigits')

If you want to convert it back to json, try json.dumps(request.POST) , or modify the requests code to convert the dictionary into a json string before sending it:

requests.post('http://localhost:8000/api/v1.0/balance/deposit/',
              data=json.dumps(data))

Requests POSTs data as form-encoded data. That's what you get in deposit . If you want to post JOSN, encode data before posting.

r = requests.post(url, data=json.dumps(data))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM