Rand Stats




URI::Query::FromHash - Construct a query string from a hash


use URI::Query::FromHash;

say hash2query {
   foo  => 'bar',
   baz  => < qux quux >,
   utf8 => '🦋',
# baz=qux&baz=quux&foo=bar&utf8=%F0%9F%A6%8B


URI::Query::FromHash aims to be a fast and lightweight query string constructor, that does the smallest amount of escaping as possible.

Inspired by the Perl module of the same name and Ruby on Rails' to_query hash method.



sub hash2query ( Hash() $hash --> Str )

Accepts anything that can be coerced to a Hash of query parameters and returns a Str suitable to be used as the query parameters of a URI.

Pairs in the input Hash will be processed alphabetically by key.

Values in the coerced Hash should be either objects that can be coerced to Str; objects that do the Blob role; Bool objects; or List objects whose elements are any of the ones specified before.

Every value (or element in a List) will appear in the generated query string once, preceded by the corresponding URL-encoded key and an equal sign (C<=>).

If it is a Blob, it will be URL-encoded per byte, with any byte that does not map to an ASCII period (.), underscore (_), hyphen (-), tilde (~), or alphanumeric character being percent-encoded (that is, represented by a percent sign (%) followed by the hexadecimal representation of the byte in uppercase).

Bool objects will be rendered as 1 if true or 0 if false.

Otherwise, it will be coerced to Str, encoded as UTF-8 and URL-encoded like above.

When this function encounters input it cannot handle, it returns the empty string, meaning it should always be safe to use.

This function is exported by default, but it can be used as a package subroutine if desired.


Copyright © 2022 by Raku Land authors

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.