Debian Codegraph @

t/sl_json_ast.t

raw
1 #!/usr/bin/perl
2 # Copyright 2022 Jeffrey Kegler
3 # This file is part of Marpa::R2. Marpa::R2 is free software: you can
4 # redistribute it and/or modify it under the terms of the GNU Lesser
5 # General Public License as published by the Free Software Foundation,
6 # either version 3 of the License, or (at your option) any later version.
7 #
8 # Marpa::R2 is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser
14 # General Public License along with Marpa::R2. If not, see
15 # http://www.gnu.org/licenses/.
16
17 # Test using a JSON parser
18 # Inspired by a parser written by Peter Stuifzand
19
20 use 5.010001;
21 use strict;
22 use warnings;
23 use Test::More tests => 15;
24
25 ## no critic (ErrorHandling::RequireCarping);
26
27 use Marpa::R2;
28
29 my $p = MarpaX::JSON->new;
30
31 my $data = $p->parse_json(q${"test":"1"}$);
32 is($data->{test}, 1);
33
34 {
35 my $test = q${"test":[1,2,3]}$;
36 $data = $p->parse_json(q${"test":[1,2,3]}$);
37 is_deeply( $data->{test}, [ 1, 2, 3 ], $test );
38 }
39
40 $data = $p->parse_json(q${"test":true}$);
41 is($data->{test}, 1);
42
43 $data = $p->parse_json(q${"test":false}$);
44 is($data->{test}, '');
45
46 $data = $p->parse_json(q${"test":null}$);
47 is($data->{test}, undef);
48
49 $data = $p->parse_json(q${"test":null, "test2":"hello world"}$);
50 is($data->{test}, undef);
51 is($data->{test2}, "hello world");
52
53 $data = $p->parse_json(q${"test":"1.25"}$);
54 is($data->{test}, '1.25', '1.25');
55
56 $data = $p->parse_json(q${"test":"1.25e4"}$);
57 is($data->{test}, '1.25e4', '1.25e4');
58
59 $data = $p->parse_json(q$[]$);
60 is_deeply($data, [], '[]');
61
62 $data = $p->parse_json(q${}$);
63 is_deeply($data, {}, '{}');
64
65 $data = $p->parse_json(<<'JSON');
66 [
67 {
68 "precision": "zip",
69 "Latitude": 37.7668,
70 "Longitude": -122.3959,
71 "Address": "",
72 "City": "SAN FRANCISCO",
73 "State": "CA",
74 "Zip": "94107",
75 "Country": "US"
76 },
77 {
78 "precision": "zip",
79 "Latitude": 37.371991,
80 "Longitude": -122.026020,
81 "Address": "",
82 "City": "SUNNYVALE",
83 "State": "CA",
84 "Zip": "94085",
85 "Country": "US"
86 }
87 ]
88 JSON
89 is_deeply($data, [
90 { "precision"=>"zip", Latitude => "37.7668", Longitude=>"-122.3959",
91 "Country" => "US", Zip => 94107, Address => '',
92 City => "SAN FRANCISCO", State => 'CA' },
93 { "precision" => "zip", Longitude => "-122.026020", Address => "",
94 City => "SUNNYVALE", Country => "US", Latitude => "37.371991",
95 Zip => 94085, State => "CA" }
96 ], 'Geo data');
97
98 $data = $p->parse_json(<<'JSON');
99 {
100 "Image": {
101 "Width": 800,
102 "Height": 600,
103 "Title": "View from 15th Floor",
104 "Thumbnail": {
105 "Url": "http://www.example.com/image/481989943",
106 "Height": 125,
107 "Width": "100"
108 },
109 "IDs": [116, 943, 234, 38793]
110 }
111 }
112 JSON
113 is_deeply($data, {
114 "Image" => {
115 "Width" => 800, "Height" => 600,
116 "Title" => "View from 15th Floor",
117 "Thumbnail" => {
118 "Url" => "http://www.example.com/image/481989943",
119 "Height" => 125,
120 "Width" => 100,
121 },
122 "IDs" => [ 116, 943, 234, 38793 ],
123 }
124 }, 'is_deeply test');
125
126 my $big_test = <<'JSON';
127 {
128 "source" : "<a href=\"http://janetter.net/\" rel=\"nofollow\">Janetter</a>",
129 "entities" : {
130 "user_mentions" : [ {
131 "name" : "James Governor",
132 "screen_name" : "moankchips",
133 "indices" : [ 0, 10 ],
134 "id_str" : "61233",
135 "id" : 61233
136 } ],
137 "media" : [ ],
138 "hashtags" : [ ],
139 "urls" : [ ]
140 },
141 "in_reply_to_status_id_str" : "281400879465238529",
142 "geo" : {
143 },
144 "id_str" : "281405942321532929",
145 "in_reply_to_user_id" : 61233,
146 "text" : "@monkchips Ouch. Some regrets are harsher than others.",
147 "id" : 281405942321532929,
148 "in_reply_to_status_id" : 281400879465238529,
149 "created_at" : "Wed Dec 19 14:29:39 +0000 2012",
150 "in_reply_to_screen_name" : "monkchips",
151 "in_reply_to_user_id_str" : "61233",
152 "user" : {
153 "name" : "Sarah Bourne",
154 "screen_name" : "sarahebourne",
155 "protected" : false,
156 "id_str" : "16010789",
157 "profile_image_url_https" : "https://si0.twimg.com/profile_images/638441870/Snapshot-of-sb_normal.jpg",
158 "id" : 16010789,
159 "verified" : false
160 }
161 }
162 JSON
163 $data = $p->parse_json($big_test);
164
165 is_deeply $data, eval q{
166 {
167 'source' => '<a href="http://janetter.net/" rel="nofollow">Janetter</a>',
168 'geo' => {},
169 'in_reply_to_user_id_str' => '61233',
170 'id_str' => '281405942321532929',
171 'entities' => {
172 'hashtags' => [],
173 'media' => [],
174 'user_mentions' => [
175 {
176 'name' => 'James Governor',
177 'id' => '61233',
178 'id_str' => '61233',
179 'indices' => [
180 '0',
181 '10'
182 ],
183 'screen_name' => 'moankchips'
184 }
185 ],
186 'urls' => []
187 },
188 'created_at' => 'Wed Dec 19 14:29:39 +0000 2012',
189 'in_reply_to_status_id_str' => '281400879465238529',
190 'text' => '@monkchips Ouch. Some regrets are harsher than others.',
191 'user' => {
192 'protected' => '',
193 'name' => 'Sarah Bourne',
194 'verified' => '',
195 'id' => '16010789',
196 'id_str' => '16010789',
197 'profile_image_url_https' => 'https://si0.twimg.com/profile_images/638441870/Snapshot-of-sb_normal.jpg',
198 'screen_name' => 'sarahebourne'
199 },
200 'in_reply_to_user_id' => '61233',
201 'id' => '281405942321532929',
202 'in_reply_to_status_id' => '281400879465238529',
203 'in_reply_to_screen_name' => 'monkchips'
204 }
205 }, "big test";
206
207 $data = $p->parse_json(<<'JSON');
208 { "test": "\u2603" }
209 JSON
210 is($data->{test}, "\x{2603}", 'Unicode char');
211
212 package MarpaX::JSON;
213
214 sub new {
215
216 my ($class) = @_;
217
218 my $parser = bless {}, $class;
219
220 $parser->{grammar} = Marpa::R2::Scanless::G->new(
221 {
222 source => \(<<'END_OF_SOURCE'),
223
224 :default ::= action => [name, value]
225 lexeme default = action => [name, value]
226
227 json ::= object
228 | array
229
230 object ::= ('{' '}')
231 | ('{') members ('}')
232
233 members ::= pair* separator => [,]
234
235 pair ::= string (':') value
236
237 value ::= string
238 | object
239 | number
240 | array
241 | 'true'
242 | 'false'
243 | 'null'
244
245
246 array ::= ('[' ']')
247 | ('[') elements (']')
248
249 elements ::= value+ separator => [,]
250
251 number ~ int
252 | int frac
253 | int exp
254 | int frac exp
255
256 int ~ digits
257 | '-' digits
258
259 digits ~ [\d]+
260
261 frac ~ '.' digits
262
263 exp ~ e digits
264
265 e ~ 'e'
266 | 'e+'
267 | 'e-'
268 | 'E'
269 | 'E+'
270 | 'E-'
271
272 string ::= lstring
273
274 lstring ~ quote in_string quote
275 quote ~ ["]
276 in_string ~ in_string_char*
277 in_string_char ~ [^"] | '\"'
278
279 :discard ~ whitespace
280 whitespace ~ [\s]+
281
282 END_OF_SOURCE
283 }
284 );
285
286 return $parser;
287 }
288
289 sub parse {
290 my ( $parser, $string ) = @_;
291
292 my $re = Marpa::R2::Scanless::R->new(
293 { grammar => $parser->{grammar},
294 }
295 );
296 $re->read( \$string );
297 my $ast = ${ $re->value() };
298 return $parser->decode ( $ast );
299 } ## end sub parse
300
301 sub decode {
302 my $parser = shift;
303
304 my $ast = shift;
305
306 if (ref $ast){
307 my ($id, @nodes) = @$ast;
308 if ($id eq 'json'){
309 $parser->decode(@nodes);
310 }
311 elsif ($id eq 'members'){
312 return { map { $parser->decode($_) } @nodes };
313 }
314 elsif ($id eq 'pair'){
315 return map { $parser->decode($_) } @nodes;
316 }
317 elsif ($id eq 'elements'){
318 return [ map { $parser->decode($_) } @nodes ];
319 }
320 elsif ($id eq 'string'){
321 return decode_string( substr $nodes[0]->[1], 1, -1 );
322 }
323 elsif ($id eq 'number'){
324 return $nodes[0];
325 }
326 elsif ($id eq 'object'){
327 return {} unless @nodes;
328 return $parser->decode($_) for @nodes;
329 }
330 elsif ($id eq 'array'){
331 return [] unless @nodes;
332 return $parser->decode($_) for @nodes;
333 }
334 else{
335 return $parser->decode($_) for @nodes;
336 }
337 }
338 else
339 {
340 if ($ast eq 'true' or $ast eq 'false'){ return $ast eq 'true' }
341 elsif ($ast eq 'null' ){ return undef }
342 else { warn "unknown scalar <$ast>"; return $ast }
343 }
344 }
345
346 sub parse_json {
347 my ($parser, $string) = @_;
348 return $parser->parse($string);
349 }
350
351 sub decode_string {
352 my ($s) = @_;
353
354 $s =~ s/\\u([0-9A-Fa-f]{4})/chr(hex($1))/egxms;
355 $s =~ s/\\n/\n/gxms;
356 $s =~ s/\\r/\r/gxms;
357 $s =~ s/\\b/\b/gxms;
358 $s =~ s/\\f/\f/gxms;
359 $s =~ s/\\t/\t/gxms;
360 $s =~ s/\\\\/\\/gxms;
361 $s =~ s{\\/}{/}gxms;
362 $s =~ s{\\"}{"}gxms;
363
364 return $s;
365 } ## end sub decode_string
366
367 1;