烧瓶解码数据

时间:2018-07-31 14:58:21

标签: python flask request decode

我有这个API:

@app.route("/api/flask/market/calculate", methods=['GET'])
def get_test_calculation():
    print(request.args.get("company-data"))
    return request.args.get("company-data")

此API由附加了JSON的SpringBoot服务器请求调用。

似乎以以下形式返回数据:

%5B%7B%22id%22:1,%22companyName%22:%22Apple%22,%22marketType%22:%22Technology%22,%22country%22:%22USA%22,%22priceChange%22:%22 1.5%25%22

如何解码此字符串以摆脱%22等格式,将其格式化为JSON。

谢谢

感谢吉姆·赖特(Jim Wright)为我指明了正确的方向。这可行:

import urllib.parse
url_decoded = urllib.parse.unquote(url_encoded)
company_data = json.loads(url_decoded)

1 个答案:

答案 0 :(得分:3)

在@jackabe的情况下,似乎JSON数据作为URL编码的JSON字符串发送。

要从查询参数中解码JSON公司数据,只要JSON的格式正确(@jackabe的示例缺少结尾的}]),以下内容将起作用。

import json
import urllib

@app.route("/api/flask/market/calculate", methods=['GET'])
def get_test_calculation():
    url_encoded = request.args.get('company-data')
    url_decoded = urllib.unquote(url_encoded).decode('utf8')
    company_data = json.loads(url_decoded)
    print(company_data)
    return company_data

在您的示例中,您的查询参数实际上不是有效的JSON字符串。

import urllib
t = '%5B%7B%22id%22:1,%22companyName%22:%22Apple%22,%22marketType%22:%22Technology%22,%22country%22:%22USA%22,%22priceChange%22:%22 1.5%25%22'
decoded = urllib.unquote(t).decode('utf-8')
print(decoded)

输出(缺少结尾}]%7D%5D):

[{"id":1,"companyName":"Apple","marketType":"Technology","country":"USA","priceChange":" 1.5%"

在Python 3中,您应该执行以下操作来解码var:

from urllib.parse import unquote
decoded = unquote(t)