1

I am able to parse url using urlsplit and get parameters using query argument.

url is '/api/v1/test?par1=val1&par2=val2a%3D1%26val2b%3Dfoo%26val2c%3Dbar'

After using urlsplit and query I get

'par1=val1&par2=val2a%3D1%26val2b%3Dfoo%26val2c%3Dbar'

And after running parse_qs on above I get

{'par2': ['val2a=1&val2b=foo&val2c=bar'], 'par1': ['val1']}

Here is output which is exactly what I need

'par1': ['val1']

I get return as list for one of parameter which has decoded data as below

'par2': ['val2a=1&val2b=foo&val2c=bar]

I can split par2 using split method at & and = and get val2a...

But is there any better way for this?

3
  • 1
    Please add the url which you are parsing as well. Commented Apr 29, 2016 at 17:47
  • @AKS updated with url Commented Apr 29, 2016 at 17:56
  • Please check my answer. Commented Apr 29, 2016 at 18:10

2 Answers 2

2

You can again use parse_qs on the value of par2

>>> url = '/api/v1/test?par1=val1&par2=val2a%3D1%26val2b%3Dfoo%26val2c%3Dbar'
>>> q = parse_qs(urlparse(url).query)
>>> q
{'par2': ['val2a=1&val2b=foo&val2c=bar'], 'par1': ['val1']}
>>> parse_qs(q['par2'][0])
{'val2b': ['foo'], 'val2c': ['bar'], 'val2a': ['1']}

After the last result you can get the value of val2a etc.

Sign up to request clarification or add additional context in comments.

Comments

1

split on & and partition on = is probably the easiest and most efficient way.

result = {k: v for k, _, v in (pair.partition('=') for pair in values.split('&'))}
# or
result = dict(pair.split('=') for pair in values.split('&'))

Using re.sub() is another option but I believe it's just over complicating stuff.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.