Converting x-www-form-urlencoded query string to a dict

Asked
Active3 hr before
Viewed126 times

7 Answers

convertingquerystringurlencoded
90%

Use our free online tool to encode any string to url encoded format,,Also Read: How to decode URL components in Python,In this article, you’ll learn how to encode URL components in Python

Example_snippet/controller/utility/_converting.js/ >>> import urllib.parse >>> qu. . .
>>>
import urllib.parse >>>
   query = 'Hellö Wörld@Python' >>>
   urllib.parse.quote(query)
'Hell%C3%B6%20W%C3%B6rld%40Python'
load more v
88%

Which means you can easily convert it into an array of name/value pairs:,But what if you want to send a form as application/x-www-form-urlencoded? Well…,The constructor also accepts an array of name/value pairs, or an iterator that yields name/value pairs:,URLSearchParams handles encoding and decoding application/x-www-form-urlencoded data, It's pretty handy, because, well…

Example_snippet/controller/utility/_converting.js/ async function isPositive(text. . .
async function isPositive(text) {
   const response = await fetch(`http://text-processing.com/api/sentiment/`, {
      method: 'POST',
      body: `text=${text}`,
      headers: {
         'Content-Type': 'application/x-www-form-urlencoded',
      },
   });
   const json = await response.json();
   return json.label === 'pos';
}
load more v
72%

HTML forms by default use application/x-www-form-urlencoded content type for sending parameters, You need to decode the received parameters before using them in your Python applications

Example_snippet/controller/utility/_converting.js/ >>> import urllib.parse >>> en. . .
>>>
import urllib.parse >>>
   encodedStr = 'Hell%C3%B6%20W%C3%B6rld%40Python' >>>
   urllib.parse.unquote(encodedStr)
'Hellö Wörld@Python'
load more v
65%

Example_snippet/controller/utility/_converting.js/ Map<String, String> body = {. . .
  Map<String, String> body = {
    'name': 'doodle',
    'color': 'blue',
    'homeTeam': json.encode(
      {'team': 'Team A'},
    ),
    'awayTeam': json.encode(
      {'team': 'Team B'},
    ),
  };

  Response r = await post(
    url,
    body: body,
  );
load more v
75%

Is it possible to add x-www-form-urlencoded params in URL Component (for example with QueryItem) ?,I am trying to do a sign in / sign up form and I want the username and the password to be x-www-form-urlencoded,,request

Example_snippet/controller/utility/_converting.js/ func signIn(for username : Str. . .
func signIn(for username : String, for password : String, completion: ((Result<User>) -> Void)?) {
        urlComponents.path = "/users/signin/"
        urlComponents.queryItems = [userIdItem]
        guard let url = urlComponents.url else { fatalError("Could not create URL from components") }
        
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)
        let task = session.dataTask(with: request) { (responseData, response, responseError) in
            DispatchQueue.main.async {
                if let error = responseError {
                    completion?(.failure(error))
                } else if let jsonData = responseData {
                    let decoder = JSONDecoder()
                    
                    do {
                        let user = try decoder.decode(User.self, from: jsonData)
                        completion?(.success(user))
                    } catch {
                        completion?(.failure(error))
                    }
                } else {
                    let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : "Data was not retrieved from request"]) as Error
                    completion?(.failure(error))
                }
            }
        }
        
        task.resume()
    }
load more v
40%

Set the Content-Type header to application/x-www-form-urlencoded,,Typically, you want to send some form-encoded data — much like an HTML form

Example_snippet/controller/utility/_query.js/ >>> r = requests.post(URL, dat. . .
>>> r = requests.post(URL, data = {
   'key': 'value'
})
load more v
22%

Currently using this to manually converting it into 'real' python dict, However, there still might be unknown problems that I haven't met yet

Example_snippet/controller/utility/_query.js/ from urllib.parse import parse. . .
from urllib.parse
import parse_qs

str_raw_data = str(bytes_raw_data, 'utf-8') # bytes to string

formatted_data_dict = parse_qs(str_raw_data)
data = {}
for k, v in formatted_data_dict.items():
   if len(v) == 1:
   data[k] = v[0]
else :
   data[k] = v

return data