简体   繁体   English

如何接受 GET 请求并将其转换为 JSON object?

[英]How do I take a GET request and turn it into a JSON object?

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.我实际上不想对网站进行任何调用,但我必须接受此 GET 请求并将其转换为 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"}

I've built a simple function for this before which uses urllib :我为此构建了一个简单的 function 之前使用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( " )您需要将 url 包含在引号内( "

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:请注意,根据您使用urrlib的 python 版本,可能会引发错误:

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

# python 2
import urllib
...
key, val = urllib.unquote(data).split("=")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM