in reply to Re^11: Converting hash into js object properties
in thread Converting hash into js object properties

OK, after some trial and error, I came up with this:

sub hash_walk { my ($hash, $string, $level, %keys_printed) = @_; while (my ($k, $v) = each %$hash) { $string .= "{ $k: " unless $keys_printed{$level}{$k}; $keys_printed{$level}{$k} = 1; if (ref($v) eq 'HASH') { $string = hash_walk($v, $string, ++$level, %keys_printed); $string .= ' }, '; $level--; } else { $string .= $v . ' },'; } } return $string; } my %data = ( email =>{steve => 'owens'}, user => {steve => {fun => 'times', laugh => 'in'}}, pass => {blah => 'moomoo'}, ); print hash_walk(\%data, '', 0, ()) . "\n";

Now I just need to come up with some code to properly handle the quoting of the values.

$PM = "Perl Monk's";
$MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate";
$nysus = $PM . ' ' . $MCF;
Click here if you love Perl Monks

Replies are listed 'Best First'.
Re^13: Converting hash into js object properties
by roboticus (Chancellor) on Nov 22, 2017 at 20:46 UTC

    nysus:

    That looks like a good start. I find myself writing variations of that from time to time.

    For checking when you need to quote values, I suggest looking at Scalar::Utils--it provides the function looks_like_number() which I use all the time to do things like that:

    $val = wrap($val, '"') if defined $val and length($val) and ! looks_li +ke_number($val);

    You may also want to handle the array case, as well as protect yourself in the event that your keys aren't legal keys in javascript (i.e., have blanks, punctuation, etc.).

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re^13: Converting hash into js object properties
by huck (Prior) on Nov 22, 2017 at 05:27 UTC

    Now I just need to come up with some code to properly handle the quoting of the values.

    In no way am i actually admitting that ive been known to steal code from Data::Dumper to do things like that, but that would be perl quoting

      Heh, I thought about doing that. Didn't want to steal the opportunity from myself to agonize over my goofy hack. :) I'll look now to see how a pro would do it.

      $PM = "Perl Monk's";
      $MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate";
      $nysus = $PM . ' ' . $MCF;
      Click here if you love Perl Monks