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

Question:

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?

Asked By: Wesley

||

Answers:

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.

Answered By: Jieter

A quote is not part of a string

It’s up to you which quote you use and it is up to Python which quote it uses.

>>> 'asdf'
'asdf'
>>> "asdf"
'asdf'
>>> "as'df"
"as'df"
Answered By: pacholik

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')
Answered By: Павел
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.