-1

I don't actually want to make any calls to a website but I have to take this GET request and turn it into a JSON object.

?goal=NOT_GOAL_SETTING&kpi=lfa&sec_kpi=not_being_used&numdays=31&budget=13000000&channel=not_being_used&channel_max=not_being_used&brand=Ram&nameplate=namplate1_nameplate2_&target=800000&nameplate_min_spend=0_0_0_0_0_0_0&nameplate_max_spend=0_0_0_0_0_0_0&max_lfas=70000_100000_4000_400000_90000_15000_2000&search_digital_min_spend=0_0&search_digital_max_spend=0_0&search_digital_min_lfas=0_0&search_digital_max_lfas=0_0

I want every variable that is defined after the = and I want to split the variables by _.

A smaller request is like this-

?variable1=1_2_3_4&variable2=string

What I want is the following:

{"variable1":[1,2,3,4], "variable2":"string"}
Ravaal
  • 3,233
  • 6
  • 39
  • 66
  • Please provide a smaller (but still representativ) input sample, and what, exactly, you want the output generated from it to look like. – Amitai Irron May 12 '20 at 16:23
  • [urllib.parse.parse_qs](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.parse_qs) might be a good starting point. – chash May 12 '20 at 16:24
  • Ok I edited the question. – Ravaal May 12 '20 at 16:25
  • Where are you getting this GET request ? Is this the request body from a request someone makes on your server or is it just an arbitrary GET url ? – fixatd May 12 '20 at 16:33
  • It's being sent to the command line as an argument. `python app.py ?goal=102&value=1_0_0_0`. Right now the problem that I'm facing is that the command prompt ignores anything after a `&`. – Ravaal May 12 '20 at 17:11

1 Answers1

1

I've built a simple function for this before which uses urllib:

import sys
import urllib.parse

def parseGetUrl(url):
    result = {}
    for data in url.split("&"):
        key, val = urllib.parse.unquote(data).split("=")            
        if val.find('_') != -1:
            val = val.split('_')
        result[key] = val
    return result

if __name__ == "__main__":
    url = sys.argv[1][1:] # Gets argument then removes ?   
    parsedData = parseGetUrl(url)
    print(parsedData)

You need to wrap your url inside quotes(")

python3 app.py "?goal=102&value=1_0_0_0"

Do note though that depending on which python version you use urrlib might throw an error:

# python 3
import urrlib.parse
...
key, val = urllib.parse.unquote(data).split("=")

# python 2
import urllib
...
key, val = urllib.unquote(data).split("=")
fixatd
  • 1,394
  • 1
  • 11
  • 19