-1

I want to parse an array of objects in a url into Python. I have tried using a url like this:

url = "?query[]=item1&query[]=item2&query=item3"

and request.args.get('query') returns None I have also tried using a url like this:

url = "?query=item1&query=item2&query=item3"

and request.args.get('query') only returns item 1. What is the best way parse the url into a list of items?

Lewis
  • 35
  • 7
JJ mantle
  • 23
  • 1
  • 4
  • maybe duplicated with this. https://stackoverflow.com/questions/21584545/url-query-parameters-to-dict-python – Lewis Apr 21 '19 at 23:46
  • Possible duplicate of [Retrieving parameters from a URL](https://stackoverflow.com/questions/5074803/retrieving-parameters-from-a-url) – Error - Syntactical Remorse Apr 21 '19 at 23:50
  • I'm not sure if you need "how to parse url" or "how to generate url with many values in one variable which flask could parse correctly". it is two different problems. – furas Apr 22 '19 at 00:24

2 Answers2

0

While this is almost definitely the wrong way to do this, it should still work.

parsed = [x.split("=")[1] for x in url[1:].split("&")]

I would recommend looking at some of the other answers to use a library with more robust and consistent capabilities.

azb_
  • 387
  • 2
  • 10
0

Try getlist()

print(request.args)
print(request.args.getlist('query'))   
print(request.args.getlist('query[]')) 

For ?query[]=item1&query[]=item2&query=item3" it gives

ImmutableMultiDict([('query[]', 'item1'), ('query[]', 'item2'), ('query', 'item3')])
['item3'] # query
['item1', 'item2'] # query[]

For ?query=item1&query=item2&query=item3" it gives

ImmutableMultiDict([('query', 'item1'), ('query', 'item2'), ('query', 'item3')])
['item1', 'item2', 'item3'] # query
[] # query[]
furas
  • 134,197
  • 12
  • 106
  • 148