Question

I need to get a readable JSON object from a PERL script but it's not in a readable format.

This is the code that produces the JSON.

            while (my ($orderID, $possessorName, $itemDescription, $customerPickUpTime, $customerDropOffTime, $paymentAmount, $originAddress1, $originAddress2, $originNeighborhood, $originZipCode, $destinationAddress1, $destinationAddress2, $destinationNeighborhood, $destinationZipCode) = $sth->fetchrow_array) 
        {
            %data = (orderID => $orderID, possessorName => $possessorName, itemDescription => $itemDescription, customerPickUpTime => $customerPickUpTime, customerDropOffTime => $customerDropOffTime, paymentAmount => $paymentAmount, originAddress1 => $originAddress1, originAddress2 => $originAddress2, originNeighborhood => $originNeighborhood, originZipCode => $originZipCode, destinationAddress1 => $destinationAddress1, destinationAddress2 => $destinationAddress2, destinationNeighborhood => $destinationNeighborhood, destinationZipCode => $destinationZipCode);


            $json_obj = JSON->new->allow_nonref;

            my $json_text = $json_obj->pretty->encode(\%data);

            $query_results{"job$index"} = {"data" => $json_text};

            $index++;

        }




        return $json_obj->pretty->encode(\%query_results, {ascii => 1, pretty => 1});

Everything works except when I look into the file (here's the printing line):

 open (resultsFile, ">", "json_file.txt") || die "This doesn't work.";

 print resultsFile "Results: \n\n $results";

The results are as follows:

       {
    "job3" : {
  "data" : "{\n   \"originAddress1\" : \"101 East 105th Street\",\n   \"destinationZipCode\" : \"10128\",\n   \"destinationNeighborhood\" : \"Upper East Side\",\n   \"customerDropOffTime\" : \"2013-01-22 23:41:37\",\n   \"originAddress2\" : \"\",\n   \"paymentAmount\" : \"19.00\",\n   \"customerPickUpTime\" : \"2013-01-22 22:56:37\",\n   \"itemDescription\" : \"body\",\n   \"destinationAddress1\" : \"180 East 93rd Street\",\n   \"destinationAddress2\" : \"\",\n   \"possessorName\" : \"Lisa Howard\",\n   \"originZipCode\" : \"10029\",\n   \"originNeighborhood\" : \"East Harlem\",\n   \"orderID\" : \"723\"\n}\n"
},

The JSON object is formed correctly but the \n is the problem. It's not outputting with an actual newline. That's the issue.

Was it helpful?

Solution

This is because, $json_text is a string and not a hash. If you want to encode the whole thing as JSON, you must create an appropriate data structure

$query_results{"job$index"} = {"data" => \%data};

and give that as a whole to encode.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top