Caveats apply. This is not recursive and it almost certainly should be; it fails on deeper data structures. It only serializes. I am almost positive there is something in some corner of the CPAN that does this but I couldn't find it in a somewhat casual search. This is first draft quality code. This style of query string is popular with PHP and Ruby apps. I think this is how jQuery does it if you don't request "traditional" (meaning *standards compliant* serialization) so it might be good to just copy its code if there turns out to be nothing solid in Perl already.
use strictures;
use Carp;
use URI::Escape;
my %hash = ( "name" => "test name",
"file_ids" => [ 1, 2 ],
"sub" => { "name" => "foo",
"message" => "bar" } );
print serialize_web2_0_query_string(\%hash), $/;
sub serialize_web2_0_query_string {
no warnings "uninitialized";
my $datum = shift;
my $strings = shift || [];
for my $key ( keys %$datum )
{
if ( ref $datum->{$key} eq "HASH" )
{
while ( my ( $k, $v ) = each %{ $datum->{$key} } )
{
push @$strings, sprintf "%s[%s]=%s", uri_escape($key),
+ uri_escape($k), uri_escape($v);
}
}
elsif ( ref $datum->{$key} eq "ARRAY" )
{
push @$strings, sprintf "%s[]=%s", uri_escape($key), uri_e
+scape($_) for @{ $datum->{$key} };
}
elsif ( not ref $datum->{$key} )
{
push @$strings, join "=", map uri_escape($_), $key, $datum
+->{$key};
}
else
{
croak "Nope. Don't know what to do with ", $key, " => ", $
+datum->{$key};
}
}
return join "&", @$strings
}
__DATA__
sub[name]=foo&sub[message]=bar&file_ids[]=1&file_ids[]=2&name=test%20n
+ame
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
|
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|