perl: item= to head2=
[aurutils.git] / perl / AUR / Json.pm
blob23b8afe50a71f04875b277999e685bb66e73f2bb
1 package AUR::Json;
2 use strict;
3 use warnings;
4 use v5.20;
6 use Exporter qw(import);
7 our @EXPORT_OK = qw(parse_json parse_json_aur write_json);
8 our $VERSION = 'unstable';
10 =head1 NAME
12 AUR::Json - Perl interface to AurJson
14 =head1 SYNOPSIS
16 use AUR::Json qw(parse_json_aur write_json);
18 my $json;
19 my @results = parse_json_aur($json);
20 my $object = parse_json($json);
21 my $str = write_json($object);
23 =head1 DESCRIPTION
25 This module provides Perl aur(1) scripts a coherent way to deal with
26 AurJson responses. In particular, parse_json_aur() returns an array of
27 package results for variable AUR inputs (both from AurJson and
28 metadata archives.
30 If JSON::XS is available, this module will use it for JSON
31 parsing. JSON::PP shipped with Perl is used as a fallback.
33 TODO: The interface is in its early stages and is prone to change in
34 later versions. Possible additions include AUR types for common use
35 with aur-format(1) and aur-search(1).
37 =head1 AUTHORS
39 Alad Wenter <https://github.com/AladW/aurutils>
41 =cut
43 our $aur_json;
45 # Fallback to slower perl-based JSON parsing
46 if (eval { require JSON::XS; 1 }) {
47 $aur_json = JSON::XS->new;
49 else {
50 require JSON::PP;
51 $aur_json = JSON::PP->new;
54 =head2 parse_json()
56 =cut
58 sub parse_json {
59 my $str = shift;
60 my $obj = $aur_json->incr_parse($str)
61 or die __PACKAGE__ . ": expected JSON object or array at beginning of string";
62 $aur_json->incr_reset();
64 return $obj;
67 =head2 parse_json_aur()
69 =cut
71 sub parse_json_aur {
72 my $str = shift;
73 my $obj = parse_json($str);
75 # Possible AUR responses:
76 # - JSON arrays: REST (suggests), metadata archives (packages-meta-v1.json)
77 # - JSON hashes, `results` array: REST (info, search)
78 # - JSON hashes: `repo-parse` (JSONL)
79 if (ref($obj) eq 'HASH' and defined($obj->{'results'})) {
80 my $error = $obj->{'error'};
82 if (defined($error)) {
83 say STDERR __PACKAGE__ . ': response error (' . $error . ')';
84 exit(4);
86 return @{$obj->{'results'}};
88 elsif (ref($obj) eq 'HASH') {
89 return ($obj);
91 elsif (ref($obj) eq 'ARRAY') {
92 return @{$obj};
94 else {
95 say STDERR __PACKAGE__ . ": not an array or hash";
96 exit(4);
100 =head2 write_json()
102 =cut
104 sub write_json {
105 my $obj = shift;
106 my $str = $aur_json->canonical()->encode($obj);
107 return $str;
110 # vim: set et sw=4 sts=4 ft=perl: