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

Re: strings to json

by tobyink (Canon)
on Jun 23, 2017 at 13:42 UTC ( [id://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 (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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2024-04-23 16:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found