-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson2yaml
executable file
·61 lines (53 loc) · 1.01 KB
/
json2yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env perl
#
# $Id: json2yaml,v 1.13 2011/06/10 05:07:41 ryo Exp $
#
# Copyright(c) 2009 Ryo SHIMIZU <[email protected]>
#
use strict;
use warnings;
use Encode;
use JSON::XS;
use YAML::XS;
use LWP::Simple;
if ($#ARGV >= 0) {
for my $file (@ARGV) {
print "== $file ==\n" if ($#ARGV > 0);
json2yaml(scalar(fileread($file)));
}
} else {
my $file = join("", <>);
json2yaml($file);
}
exit;
sub json2yaml {
my $json = shift;
# XXX: json log hack
if ($json =~ m/,\n$/s) {
$json =~ s/,\n$//s;
$json = '[' . $json . ']';
}
my $data;
eval('$data = decode_json($json)');
unless (defined $data) {
$json = '[' . join(",", split(/\n/, $json)) . ']';
eval('$data = decode_json($json)');
}
print YAML::XS::Dump($data);
}
sub fileread {
my $file = shift;
if ($file =~ m#^(http|https|ftp)://#i) {
my $json = get($file);
unless (defined $json) {
warn "$file: error\n";
$json = '{}';
}
$json;
} else {
open my $fh, "<", $file or die "open: $file: $!\n";
local $/;
undef $/;
<$fh>;
}
}