Ibukun Muyide
Ibukun Muyide

Reputation: 1298

Formatting Django request cookies

Am trying to format the cookies result coming from the request in django.

def submitcheckout(request):
    print(request.COOKIES['cart'])

the result of the print command is

[{%22cartprice%22:%22333%22%2C%22cartimg%22:%22/media/CACHE/images/uploads/7-1_BLY84nL/ec71ea409aa7d89935e9a24ef6f7883e.jpg%22%2C%22cartname%22:%22Bat-hub%22%2C%22cartid%22:%227%22}]

Running this command also print(type(request.COOKIES['cart']))return a data type of str which shows its a string. the string is useless to me now becuase i don't know how to remove the padded %22 and the likes added to represent space. The Cookies was an array from the browser.

Have try using json.dump and json.load but none of the two worked

Upvotes: 0

Views: 604

Answers (2)

Ibukun Muyide
Ibukun Muyide

Reputation: 1298

Figured it out first use urllib to convert it to normal text, then convert load json object using json.loads() function

import urllib
import json
def submitcheckout(request):
    result = urllib.unquote(request.COOKIES['cart'])
    json_result = json.loads(result)

Upvotes: 0

Oli
Oli

Reputation: 415

You can use urllib to remove the characters described. See the code below.

import urllib
def submitcheckout(request):
    print(urllib.unquote(request.COOKIES['cart']))

Upvotes: 1

Related Questions