jackabe
jackabe

Reputation: 365

Flask decode data

I have this 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")

This API is called by a SpringBoot server request which has attached JSON.

It seems to return data in the form:

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

How do I decode this string to get rid of the %22 etc to format into JSON.

Thanks

Thanks to Jim Wright for pointing me in the right direction. This worked:

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

Upvotes: 1

Views: 5209

Answers (1)

Jim Wright
Jim Wright

Reputation: 6058

In @jackabe's case it seems that the JSON data is being sent as a URL encoded JSON string.

To decode the JSON company-data from a query parameter the following will work as long as the JSON is properly formatted (@jackabe's example is missing the closing }]).

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

In your example your query parameter is actually not a valid JSON string.

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)

Output (missing the closing }] or %7D%5D):

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

In Python 3 you should do the following to decode the var:

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

Upvotes: 4

Related Questions