Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to generate urlencoded string in Python that is valid for PHP parser

I need to generate same output in Python as I have in PHP, possible?

Php code:

<?php 

$items = array(
   array(
   'item_key_a' => 'item_value_a')
);

$payload = array(
   'i_key' => 'i_value',
   'items' => $items,
);

echo http_build_query($payload);
 ?>

Output urlencoded:

i_key=i_value&items%5B0%5D%5Bitem_key_a%5D=item_value_a

Output urldecoded:

i_key=i_value&items[0][item_key_a]=item_value_a

Python code:

item = {}
item['item_key_a'] = 'item_value_a'

data = {}
data['i_key'] = 'i_value'
data['items'] = [item]

import urllib
print urllib.urlencode(data)

Output urlencoded:

items=%5B%7B%27item_key_a%27%3A+%27item_value_a%27%7D%5D&i_key=i_value

Output urldecoded:

items=[{'item_key_a':+'item_value_a'}]&i_key=i_value

So in Python I don't get valid urlencoding that I need for PHP app.

like image 415
Anton Shishkov Avatar asked Dec 28 '25 01:12

Anton Shishkov


2 Answers

Python urlencode does not handle nested dict. You need to write it yourself in a manner such as presented for this question:

  • urlencode a multidimensional dictionary in python
like image 187
Rod Avatar answered Dec 30 '25 14:12

Rod


There now seems to be a library for handling this in Python

https://github.com/uber/multidimensional_urlencode

like image 41
sleepycal Avatar answered Dec 30 '25 14:12

sleepycal



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!