Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Perl JSON example

Posted on 2011-03-16
1
Medium Priority
?
1,892 Views
Last Modified: 2012-06-21
Trying to do basic example. Have text, turn to JSON format, take JSON format convert back to text, and print.

What is wrong with this code.

Thanks
#!/usr/bin/perl -w
use JSON -support_by_pp;
   
   
  eval{
    $content = {
name => 'bob',
country => 'US',
age => 34,
sex => 'm'
   
    };
    my $json = new JSON;
   
    # these are some nice json options to relax restrictions a bit:
    my $json_text = $json->allow_nonref->utf8->relaxed->escape_slash->loose->allow_singlequote->allow_barekey->decode($content);
   
   
    $perl_scalar = from_json( $json_text, { utf8  => 1 } );
 $pretty_printed = $json->pretty->encode( $perl_scalar );
 print " $pretty_printed";
  } ;                                                                                                                                                                                                
   
  # catch crashes:
  if($@){
    print "[[JSON ERROR]] JSON parser crashed! $@\n";
  }

Open in new window

0
Comment
Question by:freshgrill
1 Comment
 
LVL 5

Accepted Solution

by:
group0 earned 2000 total points
ID: 35152923
You're trying to decode a non-JSON string.  Change:

    my $json_text = $json->allow_nonref->utf8->relaxed->escape_slash->loose->allow_singlequote->allow_barekey->decode($content);

Open in new window


to:

    my $json_text = $json->allow_nonref->utf8->relaxed->escape_slash->loose->allow_singlequote->allow_barekey->encode($content);

Open in new window

0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Email validation in proper way is  very important validation required in any web pages. This code is self explainable except that Regular Expression which I used for pattern matching. I originally published as a thread on my website : http://www…
There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans

963 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question