Metaweb/JSONLikePerl.pm untested

filter: Statementstmt 0.0% 0 / 167 Branchbran 0.0% 0 / 96 Conditioncond 0.0% 0 / 89 MC/DCmcdc 0.0% 0 / 50 Subroutinesub 0.0% 0 / 10 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 418 CC 49 SCAR 75.7
CC
49
Cov
0%
jsonlp_traverse
2352.0
jsonlp_quote
6.0
jsonlp_fetch
2.0
CRAP 1947.0
1 package WWW::Metaweb::JSONLikePerl;
2  
3 use 5.008006;
4 use strict;
5 use warnings;
6  
7 use Exporter;
8  
9 our @ISA = qw(Exporter);
10 our @EXPORT = qw();
11 our @EXPORT_OK = qw(jsonlp_fetch jsonlp_replace jsonlp_insert jsonlp_quote jsonlp_unquote);
12 our %EXPORT_TAGS = (standard => [qw(jsonlp_fetch jsonlp_replace jsonlp_insert jsonlp_quote jsonlp_unquote)]);
13 our $VERSION = 0.01;
14  
15 =head1 NAME
16  
17 WWW::Metaweb::JSONLikePerl - Access a JSON string like a Perl structure
18  
19 =head1 SYNOPSIS
20  
21 use strict;
22 use WWW::Metaweb::JSONLikePerl qw(:standard);
23  
24 my json = qq({
25 "cover_appearances": [
26 {
27 "part_of_series": "Runaways",
28 "type": "/comic_books/comic_book_issue",
29 "name": "Runaways Vol 1 #1"
30 },
31 {
32 "part_of_series": "Runaways",
33 "type": "/comic_books/comic_book_issue",
34 "name": "Runaways Vol. 2 #1"
35 },
36 {
37 "part_of_series": "Mystic Arcana",
38 "type": "/comic_books/comic_book_issue",
39 "name": "Mystic Arcana Book IV: Fire"
40 }
41 ],
42 "name": "Nico Minoru",
43 "created_by": ["Brian K. Vaughan"],
44 "/type/object/creator": "/user/metaweb",
45 "type": "/comic_books/comic_book_character",
46 "id": "/topic/en/nico_minoru"
47 });
48  
49 my $id = $jsonlp_fetch('->{id}', $json);
50  
51 my new_json;
52  
53 $new_json = jsonlp_replace('->{cover_appearances}->[2]->{name}', $json, 'Mystic Arcana IV: Sister Grimm');
54  
55 $new_json = jsonlp_insert('->{created_by}', $json, 'Adrian Alphona');
56  
57 my $second_json = qq({
58 "query":{
59 "country":null,
60 "name":99507,
61 "type":["/location/postal_code"]
62 }
63 });
64  
65 $new_json = jsonlp_quote('->{query}->{name}', $second_json, '"');
66  
67 $new_json = jsonlp_unquote('->{query}->{type}', $second_json);
68  
69 =head1 ABSTRACT
70  
71 WWW::Metaweb::JSONLikePerl allows manipulation of a JSON string, referencing items like a perl structure, but without actually converting the string.
72  
73 =head1 EXPORTABLE FUNCTIONS
74  
75 =over
76  
77 =item B<< $value = jsonlp_fetch($structure_path, $json_string, [include_quotes]) >>
78  
79 Returns the value of the item in C<$json_string> pointed to by C<$structure_path>.
80  
81 If C<include_quotes> is true then whatever may be quoting the value being fetched will also be included, this may be 'C<{ }>' for a hash, 'C<[ ]>' for an array, 'C<" ">' for a string or make no difference if it's a number or bare word.
82  
83 =cut
84  
85 sub jsonlp_fetch {
86 my $pp = shift;
87 my $js = shift;
88 my $quoted = shift || 0;
89  
90 return jsonlp_traverse($pp, $js, { fetch_quoted => $quoted });
91 } # &jsonlp_fetch
92  
93 =item B<< $new_json = jsonlp_replace($structure_path, $json_string, $replacement_value) >>
94  
95 Replaces the specified JSON node with C<$replacement_value>.
96  
97 =cut
98  
99 sub jsonlp_replace {
100 my $pp = shift;
101 my $js = shift;
102 my $replacement = shift;
103  
104 return jsonlp_traverse($pp, $js, { replace => $replacement });
105 } # &jsonlp_replace
106  
107 =item B<< $new_json = jsonlp_insert($structure_path, $json_string, $text_to_insert) >>
108  
109 Inserts C<$text_to_insert> into the specified JSON node.
110  
111 =cut
112  
113 sub jsonlp_insert {
114 my $pp = shift;
115 my $js = shift;
116 my $insert = shift;
117  
118 return jsonlp_traverse($pp, $js, { insert => $insert });
119 } # &jsonlp_insert
120  
121 =item B<< $new_json = jsonlp_quote($structure_path, $json_string, $quote_characters) >>
122  
123 Quotes the specified node as specified by C<$quote_characters>.
124  
125 If C<$quote_characters> has a length of 1 (such as 'C<">') the specified node will be surrounded by that character (eg. C<"994002">). If it has a length of 2 (such as 'C<{}>') the first character will go before the specified node, the second character will go acter the specified node (eg. C<{994002}>). Any other number o characters and C<undef> will be returned.
126  
127 =cut
128  
129 # Actually that's a lie, you can pass an empty string for $char and it will
130 # behave the same as unquote().
131  
132 sub jsonlp_quote {
133 my $pp = shift;
134 my $js = shift;
135 my $char = shift;
136  
137 return (length $char >= 0 && length $char <= 2) ? jsonlp_traverse($pp, $js, { quote => $char }) : undef;
138 } # &jsonlp_quote
139  
140 =item B<< $new_json = jsonlp_unquote($structure_path, $json_string) >>
141  
142 Removes quotes from the specified node.
143  
144 =cut
145  
146 sub jsonlp_unquote {
147 my $pp = shift;
148 my $js = shift;
149  
150 return jsonlp_traverse($pp, $js, { quote => '' });
151 } # &jsonlp_unquote
152  
153 =back
154  
155 =head1 BUGS AND TODO
156  
157 None of either as of yet.
158  
159 =head1 ACCKNOWLEDGEMENTS
160  
161 Mainly the Barcelona weather for keeping me up late enough to come up with this crazy idea.
162  
163 =head1 SEE ALSO
164  
165 JSON, WWW::Metaweb
166  
167 =head1 AUTHORS
168  
169 Hayden Stainsby E<lt>hds@cpan.orgE<gt>
170  
171 =head1 COPYRIGHT AND LICENSE
172  
173 Copyright (C) 2007 by Hayden Stainsby
174  
175 This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
176  
177 =cut
178  
179 # jsonlp_traverse - Json like-perl traverse
180 # This function accepts a perl-like dereferencing / accessing string and a JSON
181 # string. It will either return the item pointed to - or set that item with a
182 # replacement and return the new string.
183 sub jsonlp_traverse {
184 my $pp = shift; # Perl path
185 my $js = shift; # JSON string
186 my $action = shift; # Replacement for JSON segment
187 my $super_inside = shift; # What we're inside
188 my ($path_segment, $path_index, $json_segment, $remaining_pp, $parsed_js);
189  
190 # This means we've hit the bottom of our parsing.
191 if (length $pp == 0) {
192 if (defined $action->{replace}) {
193 return $action->{replace};
194 }
195 elsif (defined $action->{insert}) {
196 my $insert = $action->{insert};
197 $insert .= ',' if length $js > 0;
198 $js =~ s/^(\s*)/$1$insert$1/;
199 return $js;
200 }
201 elsif (defined $action->{quote}) {
202 my ($lq, $rq);
203 if (length $action->{quote} == 2) {
204 $lq = substr $action->{quote}, 0, 1;
205 $rq = substr $action->{quote}, 1, 1;
206 }
207 elsif (length $action->{quote} == 1) {
208 $lq = $rq = substr $action->{quote}, 0, 1;
209 }
210 else {
211 $lq = $rq = '';
212 }
213
214 return $lq.$js.$rq;
215 }
216 else {
217 return $js;
218 }
219 }
220  
221 # Parse perl path
222 $remaining_pp = '';
223 if ($pp =~ /^->(\{.+?\})(.*)$/) {
224 $path_segment = $1;
225 $remaining_pp = $2;
226 $path_segment =~ s/[\{\}]//g;
227 }
228 elsif ($pp =~ /^->(\[\d+\])(.*)$/) {
229 $path_index = $1;
230 $remaining_pp = $2;
231 $path_index =~ s/[\[\]]//g;
232 }
233 elsif ($pp eq '->') {
234 $pp = '';
235 }
236  
237 # Parse JSON
238 my $isquoted = 0;
239 my $cur = { curly => 0, square => 0 };
240 my $begin = undef;
241 my $inside = undef;
242 my $am_a = undef;
243 my $depth = 0;
244 my $content = undef;
245 my $current_name = undef;
246 my $current_value = undef;
247 my $value_index = undef;
248 my $parse_value;
249 for (my $i = 0; $i < (length $js)+1; $i++) {
250 my $c = substr($js, $i, 1);
251 # Get the beginning count for brackets before this character.
252 $begin = { posn => $i,
253 curly => $cur->{curly},
254 square => $cur->{square} } unless defined $begin;
255
256 # Count the openning and closing of curly and square brackets,
257 # they don't count if they're in quotes.
258 if ($isquoted) {
259 if ($c eq '"') {
260 $isquoted = 0;
261 }
262 }
263 else {
264 if ($c eq '{') { $cur->{curly}++; }
265 elsif ($c eq '}') { $cur->{curly}--; }
266 elsif ($c eq '[') { $cur->{square}++; }
267 elsif ($c eq ']') { $cur->{square}--; }
268 elsif ($c eq '"') {
269 $isquoted = 1;
270 }
271 }
272  
273 # We're not inside any sort of delimiters
274 if (not defined $inside) {
275 # Check for the beginning of an object
276 if ($c eq '{') {
277 $inside = 'HASH';
278 }
279 elsif ($c eq '[') {
280 $inside = 'ARRAY';
281 }
282 elsif ($c eq '"') {
283 $inside = 'STRING';
284 }
285 elsif ($c =~ /[\d\-\+]/) {
286 $inside = 'NUMBER';
287 $depth = 1;
288 }
289 elsif ($c =~ /\w/) {
290 $inside = 'BARE';
291 $depth = 1;
292 }
293  
294 # We've entered an object, decide whether it's a key or
295 # value and set the begin hash to what sort of object
296 # we're inside.
297 if (defined $inside) {
298 $begin->{inside} = $inside;
299  
300 if ((not defined $am_a) && $inside eq 'STRING' && ((not defined $super_inside) || $super_inside ne 'ARRAY')) {
301 $am_a = 'key';
302 }
303 elsif (not defined $am_a) {
304 $am_a = 'value';
305 }
306 }
307 else {
308 # We're not inside an object, sratch begin, but
309 # if we're on a ':' then a value is coming up.
310 $begin = undef;
311 if ((not defined $am_a) && $c eq ':') {
312 $am_a = 'value';
313 }
314 }
315  
316 }
317 else {
318 # We can only end an object (leave inside) if the
319 # bracket count is the same as before the object
320 # started.
321 my $matched = 0;
322 $matched = 1 if ($begin->{curly} == $cur->{curly} && $begin->{square} == $cur->{square});
323  
324 if ($c eq '}' && $inside eq 'HASH' && $matched) {
325 $inside = undef;
326 }
327 elsif ($c eq ']' && $inside eq 'ARRAY' && $matched) {
328 $inside = undef;
329 }
330 elsif ($c eq '"' && $inside eq 'STRING' && $matched) {
331 $inside = undef;
332 }
333 elsif ($c !~ /[\d\.]/ && $inside eq 'NUMBER' && $matched) {
334 $content = substr($js, $i-$depth, $depth);
335 $i--;
336 $inside = undef;
337 }
338 elsif ($c !~ /\w/ && $inside eq 'BARE' && $matched) {
339 $content = substr($js, $i-$depth, $depth);
340 $i--;
341 $inside = undef;
342 }
343 else {
344 # We're going deeper into the object (in
345 # characters).
346 $depth++;
347 }
348  
349 $content = substr($js, $i-$depth, $depth) unless defined $inside || defined $content;
350 }
351  
352 # We've left an object (gone outside it), time to work.
353 if ((not defined $inside) && (defined $content)) {
354 #debug print "$content ($am_a)\n";
355 if ($am_a eq 'key') {
356 # If it's a key, not much work to do.
357 $current_name = $content;
358 $current_value = undef;
359 $value_index = 0;
360  
361 }
362 elsif ($am_a eq 'value') {
363 # If this is an array, increase the value_index.
364 if (defined $current_value) {
365 $value_index++;
366 }
367 else {
368 $value_index = 0;
369 }
370 $current_value = $content;
371  
372 my $returned = undef;
373 my $traversed = 0;
374  
375 # Or if there's no name for this value and we
376 # don't know what our outer structure is.
377 if ((not defined $current_name) && (not defined $super_inside)) {
378 $returned = jsonlp_traverse($pp, $content, $action, $begin->{inside});
379 $traversed = 1
380 }
381 # If this value's name or index matches the perl
382 # path (pp) we're following, recurse into it.
383 elsif (((defined $path_index) && $value_index == $path_index) || ((defined defined $path_segment) && $current_name eq $path_segment)) {
384 $returned = jsonlp_traverse($remaining_pp, $content, $action, $begin->{inside});
385 $traversed = 1;
386 }
387  
388 if ($traversed) {
389 # A value has been returned, that's
390 # good, if we were replacing something
391 # then replace it, otherwise return
392 # just the value asked for.
393 if (defined $returned) {
394 my $replace_delimeters = 0;
395 print "fucked off!\n" unless defined $remaining_pp;
396 $replace_delimeters = 1 if $begin->{inside} ne 'NUMBER' && $begin->{inside} ne 'BARE' && (length $remaining_pp) == 0;
397 if (defined $action->{replace} || defined $action->{insert} || defined $action->{quote}) {
398 my ($before, $after) = ('', '');
399  
400 $before = substr $js, 0, $begin->{posn} + (length $remaining_pp != 0 || defined $action->{insert});
401 $after = substr $js, $begin->{posn} + length($content) + ($replace_delimeters*2) + (length $remaining_pp != 0) - (defined $action->{insert});
402 $parsed_js = $before . $returned . $after;
403 }
404 else {
405 $parsed_js = $returned;
406 if (length $remaining_pp == 0 && defined $super_inside && $action->{fetch_quoted}) {
407 $parsed_js = substr($js, $begin->{posn}, (length $returned) + $replace_delimeters*2);
408 }
409 }
410 }
411  
412 # Once a traversal has been attempted,
413 # we're on our way out.
414 last;
415 }
416 } # Finished a value
417
418 # Still moving sideways, reset all these values.
419 $begin = undef;
420 $am_a = undef;
421 $content = undef;
422 $depth = 0;
423 }
424 } # iterate through each chacter
425  
426 return $parsed_js;
427 } # &jsonlp_traverse
428  
429  
430 return 1;
431 __END__