Stanimirovv
Stanimirovv

Reputation: 3172

Generating json to parse error

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);

Upvotes: 0

Views: 71

Answers (2)

Quentin
Quentin

Reputation: 943591

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 });
}

Upvotes: 8

psxls
psxls

Reputation: 6935

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.

Upvotes: -1

Related Questions