如何在没有\ n但是以可读格式的情况下在PERL中获取JSON输出?

时间:2013-02-13 02:10:47

标签: json perl newline activeperl

我需要从PERL脚本中获取可读的JSON对象,但它不是可读的格式。

这是生成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});

一切正常,除非我查看文件(这里是打印行):

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

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

结果如下:

       {
    "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"

},

JSON对象形成正确,但\n是问题所在。它没有输出实际的换行符。这就是问题所在。

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

这是因为$json_text是一个字符串而不是哈希。如果要将整个事物编码为JSON,则必须创建适当的数据结构

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

并将其作为一个整体提供给encode