in reply to strings to json

This will work:

use strict; use warnings; my $name = 'mike'; my $age = "20"; my $email = "johndeo\@test.com"; my $pass = "test"; my $resp = "{ \"$name\": $age, \"$email\": \"$pass\" }"; print $resp;

But escaping is likely to be annoying. I'd personally do something more like this:

use strict; use warnings; use JSON::PP; my $name = 'mike'; my $age = "20"; my $email = "johndeo\@test.com"; my $pass = "test"; my $resp = JSON::PP->new->encode({ $name => $age, $email => $pass, }); print $resp;

Replies are listed 'Best First'.
Re^2: strings to json
by ikegami (Patriarch) on Jun 23, 2017 at 15:06 UTC

    The first solution is broken; it suffers from JSON-injection bugs. For example, try

    my $name = 'Mike "The Coder" Smith';

    or

    my $pass = 'S3KYU\\3e';

      It's only broken if you change the other code so $name, etc are different.

      But if you change the surrounding code, it's possible to break anything.

        Are you seriously going to argue the inputs are constant? If you really believe that, why did you post such stupid solutions? You should have suggested

        use strict; use warnings; print '{ "mike": 20, "johndeo@test.com": "test" }';

        But no, the OP used variables for a reason. It's because they are variable. And because of that, your first solution is buggy.

Re^2: strings to json
by bigup401 (Pilgrim) on Jun 23, 2017 at 13:57 UTC

    thanks guys