Wesley
Wesley

Reputation: 1947

How to make urllib.urlencode use double quotes instead of single quotes?

I have a question regarding urlencode. Here is an example:

urllib.urlencode({"action":"task_exam_save_result","examid":5,"t2],False,2]],"spendTime":911},"submit":"true","summary":{"correct":0,"wrong":2}})

So, I get this:

examresult=%7B%27spendTime%27%3A+911%2C+%27choice%27%3A+%5B%5B1593%2C+%5B0%5D%2C+False%2C+783%5D%2C+%5B1591%2C+%5B2%5D%2C+False%2C+2%5D%5D%7D&submit=true&summary=%7B%27wrong%27%3A+2%2C+%27correct%27%3A+0%7D&taskid=10&action=task_exam_save_result&examid=5

Then, I copy the above string to http://tool.chinaz.com/tools/urlencode.aspx for URL decoding and get this:

examresult={'spendTime': 911, 'choice': [[1593, [0], false, 783],
[1591, [2], false, 2]]}&submit=true&summary={'wrong': 2, 'correct':
0}&taskid=10&action=task_exam_save_result&examid=5

So, every double quote becomes a single quote; why?

I want it to keep the double quotes because I have to transfer the decoded string to other programming languages, e.g. Java and Objective C, to parse, and their strings require double quotes.

How do I do this?

Upvotes: 6

Views: 6031

Answers (2)

Павел
Павел

Reputation: 121

If you need to replace ALL single quotes with double quotes, then the easiest way to do this is:

payload = {"action":"task_exam_save_result","examid":5} 
urllib.parse.urlencode(payload)
payload = payload.replace('%27', '%22')

Upvotes: 0

Jieter
Jieter

Reputation: 4229

I would not use urlencode here, but convert to JSON using json.dumps() and then use urlencode or b64encode to make it safe for use in an url.

Upvotes: 10

Related Questions