簡體   English   中英

Perl中格式錯誤的JSON字符串

[英]malformed JSON string in Perl

我正在嘗試將json文件轉換為xml。 因此,將掃描JSON目錄,如果到達該目錄,則會將其轉換為xml並移至xml目錄。

但是我收到這個錯誤

在json.pl第29行的關閉文件句柄$ fh上的readline()。
JSON.pl第34行處的字符偏移量0(在“((字符串的結尾)”之前))格式錯誤的JSON字符串,數組,對象,數字,字符串或原子都不是

json.pl

#!/usr/bin/perl

use strict;
use warnings;
use File::Copy;

binmode STDOUT, ":utf8";
use utf8;

use JSON;
use XML::Simple;

# Define input and output directories
my $indir = 'json';
my $outdir = 'xml';

# Read input directory
opendir DIR, $indir or die "Failed to open $indir";
my @files = readdir(DIR);
closedir DIR;

# Read input file in json format
for my $file (@files) 
{
my $json;
{
    local $/; #Enable 'slurp' mode
    open my $fh, "<", "$indir/$file";
    $json = <$fh>;
    close $fh;
}

# Convert JSON format to perl structures
my $data = decode_json($json);

# Output as XML
open OUTPUT, '>', "$outdir/$file" or die "Can't create filehandle: $!";
select OUTPUT; $| = 1;
print "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
print XMLout($data);
print "\n" ;
close(OUTPUT);
unlink "$indir/$file";

}

example.json

{
"Manager":
    {
        "Name" : "Mike",
        "Age": 28,
        "Hobbies": ["Music"]
     },
"employees":
    [
        {
            "Name" : "Helen",
            "Age": 26,
            "Hobbies": ["Movies", "Tennis"]
           },
        {
            "Name" : "Rich",
            "Age": 31,
            "Hobbies": ["Football"]

        }
    ]
}

您無需在open過程中檢查錯誤,也不會跳過目錄條目( readdir將返回...條目)。

如果您使用

open my $fh, "<", "$indir/$file" or die "$file: $!";

您可能會很快發現問題。

“關閉的文件句柄$ fh上的readline()”表示“ open $fh失敗,但您還是繼續前進”。

正如@cjm所指出的那樣,問題在於您正在嘗試打開和讀取目​​錄以及源目錄中的文件。

這是針對此問題的一種解決方法,並且它還使用自動autodie來避免不斷檢查所有IO操作的狀態。 我也整理了一些東西。

#!/usr/bin/perl

use utf8;
use strict;
use warnings;
use autodie;

use open qw/ :std :encoding(utf8) /;

use JSON qw/ decode_json /;
use XML::Simple qw/ XMLout /;

my ($indir, $outdir) = qw/ json xml /;

my @indir = do {
  opendir my $dh, $indir;
  readdir $dh;
};

for my $file (@indir) {

  my $infile = "$indir/$file";
  next unless -f $infile;

  my $json = do {
    open my $fh, '<', $infile;
    local $/;
    <$fh>;
  };

  my $data = decode_json($json);

  my $outfile = "$outdir/$file";
  open my $out_fh, '>', "$outdir/$file";
  print $out_fh '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>', "\n";
  print $out_fh XMLout($data), "\n";
  close $out_fh;

  unlink $infile;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM