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

Just tried that but the property keys get surrounded by quotes in the JSON output. I'm not sure if that will make a difference.

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

  • Comment on Re^2: Converting hash into js object properties

Replies are listed 'Best First'.
Re^3: Converting hash into js object properties
by roboticus (Chancellor) on Nov 21, 2017 at 16:38 UTC

    nysus:

    It will make a difference, but in a good way, as the JSON format wants keys to be wrapped in quotes: The JSON spec indicates that the object keys are strings, and that strings are wrapped in double quotes. So you should be good to go with the module.

    I personally use JSON, which as I understand it, tries to use the first of JSON::XS, JSON::PP or JSON::backportPP that it finds on your machine.

    ...roboticus

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

Re^3: Converting hash into js object properties
by haukex (Archbishop) on Nov 21, 2017 at 16:23 UTC
    my %hash = ( rules => {name => '"required"', ...

    Just tried that but the property keys get surrounded by quotes in the JSON output.

    The module is just faithfully converting your Perl data structure into a JSON one. Your Perl strings contain the double quotes, so the JSON ones do too. If you don't want that, strip the double quotes from the Perl strings before converting to JSON (or don't add them in the first place).

    Update: Sorry, I thought you were talking about the extra quotes in the values, but you meant the keys. See replies below.

      Hmm, Data::Dumper gets me very close:
      use Data::Dumper; $Data::Dumper::Pair = ' : '; $Data::Dumper::Quotekeys = 0;

      The keys are not quoted using this method. Only problem now is that the true values are printed as literals with 'true'.

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

        Data::Dumper is a debugging tool, not necessarily appropriate for serialization, especially not for JSON.

        See the documentation of JSON::MaybeXS: JSON->true and JSON->false will give you boolean values.

A reply falls below the community's threshold of quality. You may see it by logging in.