json_writer: new routines to create JSON data
Add "struct json_writer" and a series of jw_ routines to compose JSON data into a string buffer. The resulting string may then be printed by commands wanting to support a JSON-like output format. The json_writer is limited to correctly formatting structured data for output. It does not attempt to build an object model of the JSON data. We say "JSON-like" because we do not enforce the Unicode (usually UTF-8) requirement on string fields. Internally, Git does not necessarily have Unicode/UTF-8 data for most fields, so it is currently unclear the best way to enforce that requirement. For example, on Linux pathnames can contain arbitrary 8-bit character data, so a command like "status" would not know how to encode the reported pathnames. We may want to revisit this (or double encode such strings) in the future. Helped-by: Eric Sunshine <sunshine@sunshineco.com> Helped-by: René Scharfe <l.s.r@web.de> Helped-by: Wink Saville <wink@saville.com> Helped-by: Ramsay Jones <ramsay@ramsayjones.plus.com> Signed-off-by: Jeff Hostetler <jeffhost@microsoft.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
This commit is contained in:

committed by
Junio C Hamano

parent
b2453d3449
commit
75459410ed
52
t/t0019/parse_json.perl
Normal file
52
t/t0019/parse_json.perl
Normal file
@ -0,0 +1,52 @@
|
||||
#!/usr/bin/perl
|
||||
use strict;
|
||||
use warnings;
|
||||
use JSON;
|
||||
|
||||
sub dump_array {
|
||||
my ($label_in, $ary_ref) = @_;
|
||||
my @ary = @$ary_ref;
|
||||
|
||||
for ( my $i = 0; $i <= $#{ $ary_ref }; $i++ )
|
||||
{
|
||||
my $label = "$label_in\[$i\]";
|
||||
dump_item($label, $ary[$i]);
|
||||
}
|
||||
}
|
||||
|
||||
sub dump_hash {
|
||||
my ($label_in, $obj_ref) = @_;
|
||||
my %obj = %$obj_ref;
|
||||
|
||||
foreach my $k (sort keys %obj) {
|
||||
my $label = (length($label_in) > 0) ? "$label_in.$k" : "$k";
|
||||
my $value = $obj{$k};
|
||||
|
||||
dump_item($label, $value);
|
||||
}
|
||||
}
|
||||
|
||||
sub dump_item {
|
||||
my ($label_in, $value) = @_;
|
||||
if (ref($value) eq 'ARRAY') {
|
||||
print "$label_in array\n";
|
||||
dump_array($label_in, $value);
|
||||
} elsif (ref($value) eq 'HASH') {
|
||||
print "$label_in hash\n";
|
||||
dump_hash($label_in, $value);
|
||||
} elsif (defined $value) {
|
||||
print "$label_in $value\n";
|
||||
} else {
|
||||
print "$label_in null\n";
|
||||
}
|
||||
}
|
||||
|
||||
my $row = 0;
|
||||
while (<>) {
|
||||
my $data = decode_json( $_ );
|
||||
my $label = "row[$row]";
|
||||
|
||||
dump_hash($label, $data);
|
||||
$row++;
|
||||
}
|
||||
|
Reference in New Issue
Block a user