Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: Building a URL Query String from a Data Structure

by Your Mother (Archbishop)
on Feb 09, 2016 at 19:15 UTC ( #1154759=note: print w/replies, xml ) Need Help??

in reply to Building a URL Query String from a Data Structure

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

Replies are listed 'Best First'.
Re^2: Building a URL Query String from a Data Structure
by dorko (Prior) on Feb 11, 2016 at 16:29 UTC
    That works for me. You're the winner, Your Mother. I've made a couple of minor edits and included an attribution to you and a link to this thread in my comments.

    Thank you for your time and assistance. It's greatly appreciated.



    -- Yeah, I'm a Delt.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1154759]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (7)
As of 2021-03-02 21:16 GMT
Find Nodes?
    Voting Booth?
    My favorite kind of desktop background is:

    Results (63 votes). Check out past polls.