Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: strings to json

by tobyink (Abbot)
on Jun 23, 2017 at 13:42 UTC ( #1193357=note: print w/replies, xml ) Need Help??


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 (Pope) 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 (Monk) on Jun 23, 2017 at 13:57 UTC

    thanks guys

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2018-08-18 16:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Asked to put a square peg in a round hole, I would:









    Results (185 votes). Check out past polls.

    Notices?