Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to urllib.urlencode a dictionary within an array?

I'm trying to urlencode this parameter:

params = {
                              "attachments": [
                                  {
                                      "title": "output.title",
                                      "text": "output.text",
                                  }
                              ]}

urllib.urlencode(params, True)

This is what I get:

attachments=%7B%27text%27%3A+%27output.text%27%2C+%27title%27%3A+%27output.title%27%7D

This is what I'm expecting:

attachments=%5B%7B%22text%22%3A%20%22output.text%22%2C%20%22title%22%3A%22output.title%22%7D%5D

UPDATE:

I have noticed, if I disable dosec, I get something closer to what I need.

urllib.urlencode(params)

attachments=%5B%7B%27text%27%3A+%27output.text%27%2C+%27title%27%3A+%27output.title%27%7D%5D

But there are still differences %22% vs %27%

like image 701
Houman Avatar asked Mar 12 '26 20:03

Houman


1 Answers

Well %22 is the double quote (") while %27 is the simple quote ('). And urllib.urlencode simply encode a dictionary or an sequence of two-elements tuple.

So here your dictionary has attachement as key, and has the following list of dictionaries as value:

                   val = [
                              {
                                  "title": "output.title",
                                  "text": "output.text",
                              }
                          ]

But for python, that list is not a string, so it uses its representation as a string (using simple quotes):

>>> str(val)
[{'text': 'output.text', 'title': 'output.title'}]

and then urlencode that string. If you want double quotes to be Json compatible, you should use the json module:

>>> json.dumps(val)
'[{"text": "output.text", "title": "output.title"}]'

Finally it would give:

>>> urllib.urlencode({ k: json.dumps(v) for k,v in params.iteritems() })
'attachments=%5B%7B%22text%22%3A+%22output.text%22%2C+%22title%22%3A+%22output.title%22%7D%5D'

which is what you expected (apart from the order of items, but a dictionary is a hash and does not maintain order - use a sequence of pairs if you need order)

like image 104
Serge Ballesta Avatar answered Mar 14 '26 09:03

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!