【问题标题】:How do I get JSON output in PERL without \n but in a readable format?如何在没有 \n 的情况下以可读格式在 PERL 中获取 JSON 输出?
【发布时间】:2013-02-13 02:10:47
【问题描述】:

我需要从 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 是问题所在。它没有使用实际的换行符输出。这就是问题所在。

【问题讨论】:

    标签: json perl newline activeperl


    【解决方案1】:

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

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

    并将其作为一个整体交给encode

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      相关资源
      最近更新 更多