0

I am generating a Json string, which isn't generating good Json. To me it looks good, but I have a mistake somwhere. I can't find where it is and how to remove it. Here is the entire source (since it is very short).

use strict;
use warnings;
use JSON qw( decode_json );

sub getJsonStr{
    print "Enter the name of the person: ";
    my $name = <>;
    print "Enter the age of the person: ";
    my $age = <>;
    my $json = '{
            "name" :"'.$name.'",
            "age"  :"'.$age.'"
           }';
}

my $jsonStr = getJsonStr();

print $jsonStr;

my $jobj = decode_json($jsonStr);
3
  • '{"name" :"'.$name.'" ...' better written as q({"name" :"$name" ...) Commented Dec 11, 2013 at 13:11
  • @TLP … qq({"name": "$name", ...}) in order for $name to interpolate (not just q(…)). Commented Dec 11, 2013 at 13:18
  • @amon Of course, I brainfarted there. Although I would say now to use Quentin's solution instead. Commented Dec 11, 2013 at 13:21

2 Answers 2

8

Your problem is caused by not escaping inputted characters which have special meaning or which are not allowed in JSON strings.

The method you are using to input the data is guaranteed to have a new line character at the end of it. Presumably you don't want that, so you should remove it (with chomp) rather than escaping.

That doesn't stop the user entering other characters with special meaning though. If you want to generate JSON, then use a JSON library, don't just mash strings together. You're already using JSON.pm, so get the encoder from that as well as the decoder.

sub getJsonStr {
    print "Enter the name of the person: ";
    my $name = <>;
    chomp $name;
    print "Enter the age of the person: ";
    my $age = <>;
    chomp $age;
    my $json = encode_json({ name => $name, age => $age });
}
Sign up to request clarification or add additional context in comments.

Comments

-1

You must chomp your input in order to remove all trailing newlines from the $name and $age variables, before using them into your JSON. And by that I mean:

my $name = <>;
chomp $name;

my $age = <>;
chomp $age;

These newlines was the reason of your error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.