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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
|
/* json-parser.c - JSON streams parser
*
* This file is part of JSON-GLib
* Copyright (C) 2007 OpenedHand Ltd.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Author:
* Emmanuele Bassi <ebassi@openedhand.com>
*/
/**
* SECTION:json-parser
* @short_description: Parse JSON data streams
*
* #JsonParser provides an object for parsing a JSON data stream, either
* inside a file or inside a static buffer.
*/
#include "config.h"
#include <string.h>
#include "json-marshal.h"
#include "json-parser.h"
GQuark
json_parser_error_quark (void)
{
return g_quark_from_static_string ("json-parser-error");
}
#define JSON_PARSER_GET_PRIVATE(obj) \
(G_TYPE_INSTANCE_GET_PRIVATE ((obj), JSON_TYPE_PARSER, JsonParserPrivate))
struct _JsonParserPrivate
{
JsonNode *root;
JsonNode *current_node;
};
static const GScannerConfig json_scanner_config =
{
( " \t\r\n" ) /* cset_skip_characters */,
(
"_"
G_CSET_a_2_z
G_CSET_A_2_Z
) /* cset_identifier_first */,
(
G_CSET_DIGITS
"-_"
G_CSET_a_2_z
G_CSET_A_2_Z
) /* cset_identifier_nth */,
( "#\n" ) /* cpair_comment_single */,
TRUE /* case_sensitive */,
TRUE /* skip_comment_multi */,
TRUE /* skip_comment_single */,
FALSE /* scan_comment_multi */,
TRUE /* scan_identifier */,
TRUE /* scan_identifier_1char */,
FALSE /* scan_identifier_NULL */,
TRUE /* scan_symbols */,
TRUE /* scan_binary */,
TRUE /* scan_octal */,
TRUE /* scan_float */,
TRUE /* scan_hex */,
TRUE /* scan_hex_dollar */,
TRUE /* scan_string_sq */,
TRUE /* scan_string_dq */,
TRUE /* numbers_2_int */,
FALSE /* int_2_float */,
FALSE /* identifier_2_string */,
TRUE /* char_2_token */,
TRUE /* symbol_2_token */,
FALSE /* scope_0_fallback */,
};
static const gchar symbol_names[] =
"true\0"
"false\0"
"null\0";
static const struct
{
guint name_offset;
guint token;
} symbols[] = {
{ 0, JSON_TOKEN_TRUE },
{ 5, JSON_TOKEN_FALSE },
{ 11, JSON_TOKEN_NULL }
};
static const guint n_symbols = G_N_ELEMENTS (symbols);
enum
{
ERROR,
LAST_SIGNAL
};
static guint parser_signals[LAST_SIGNAL] = { 0, };
G_DEFINE_TYPE (JsonParser, json_parser, G_TYPE_OBJECT);
static guint json_parse_array (JsonParser *parser,
GScanner *scanner,
gboolean nested);
static guint json_parse_object (JsonParser *parser,
GScanner *scanner,
gboolean nested);
static void
json_parser_dispose (GObject *gobject)
{
JsonParserPrivate *priv = JSON_PARSER_GET_PRIVATE (gobject);
if (priv->root)
{
json_node_free (priv->root);
priv->root = NULL;
}
G_OBJECT_CLASS (json_parser_parent_class)->dispose (gobject);
}
static void
json_parser_class_init (JsonParserClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
g_type_class_add_private (klass, sizeof (JsonParserPrivate));
gobject_class->dispose = json_parser_dispose;
/**
* JsonParser::error:
* @parser: the parser instance that received the signal
* @error: a pointer to the #GError
*
* The ::error signal is emitted each time a #JsonParser encounters
* an error in a JSON stream.
*/
parser_signals[ERROR] =
g_signal_new ("error",
G_OBJECT_CLASS_TYPE (gobject_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (JsonParserClass, error),
NULL, NULL,
_json_marshal_VOID__POINTER,
G_TYPE_NONE, 1,
G_TYPE_POINTER);
}
static void
json_parser_init (JsonParser *parser)
{
JsonParserPrivate *priv;
parser->priv = priv = JSON_PARSER_GET_PRIVATE (parser);
priv->root = NULL;
priv->current_node = NULL;
}
static guint
json_parse_array (JsonParser *parser,
GScanner *scanner,
gboolean nested)
{
JsonParserPrivate *priv = parser->priv;
JsonArray *array;
guint token;
if (!nested)
{
/* the caller already swallowed the opening '[' */
token = g_scanner_get_next_token (scanner);
if (token != G_TOKEN_LEFT_BRACE)
return G_TOKEN_LEFT_BRACE;
}
array = json_array_new ();
token = g_scanner_get_next_token (scanner);
while (token != G_TOKEN_RIGHT_BRACE)
{
JsonNode *node = NULL;
GValue value = { 0, };
if (token == G_TOKEN_COMMA)
{
/* swallow the comma */
token = g_scanner_get_next_token (scanner);
continue;
}
/* nested object */
if (token == G_TOKEN_LEFT_CURLY)
{
JsonNode *old_node = priv->current_node;
priv->current_node = json_node_new (JSON_NODE_OBJECT);
token = json_parse_object (parser, scanner, TRUE);
node = priv->current_node;
priv->current_node = old_node;
if (token != G_TOKEN_NONE)
{
json_node_free (node);
json_array_unref (array);
return token;
}
json_array_add_element (array, node);
node->parent = priv->current_node;
token = g_scanner_get_next_token (scanner);
if (token == G_TOKEN_RIGHT_BRACE)
break;
continue;
}
/* nested array */
if (token == G_TOKEN_LEFT_BRACE)
{
JsonNode *old_node = priv->current_node;
priv->current_node = json_node_new (JSON_NODE_ARRAY);
token = json_parse_array (parser, scanner, TRUE);
node = priv->current_node;
priv->current_node = old_node;
if (token != G_TOKEN_NONE)
{
json_node_free (node);
json_array_unref (array);
return token;
}
json_array_add_element (array, node);
node->parent = priv->current_node;
token = g_scanner_get_next_token (scanner);
if (token == G_TOKEN_RIGHT_BRACE)
break;
continue;
}
switch (token)
{
case G_TOKEN_INT:
g_value_init (&value, G_TYPE_INT);
g_value_set_int (&value, scanner->value.v_int);
node = json_node_new (JSON_NODE_VALUE);
json_node_set_value (node, &value);
g_value_unset (&value);
break;
case G_TOKEN_FLOAT:
g_value_init (&value, G_TYPE_FLOAT);
g_value_set_float (&value, scanner->value.v_float);
node = json_node_new (JSON_NODE_VALUE);
json_node_set_value (node, &value);
g_value_unset (&value);
break;
case G_TOKEN_STRING:
g_value_init (&value, G_TYPE_STRING);
g_value_set_string (&value, scanner->value.v_string);
node = json_node_new (JSON_NODE_VALUE);
json_node_set_value (node, &value);
g_value_unset (&value);
break;
case JSON_TOKEN_TRUE:
case JSON_TOKEN_FALSE:
g_value_init (&value, G_TYPE_BOOLEAN);
g_value_set_boolean (&value, token == JSON_TOKEN_TRUE ? TRUE : FALSE);
node = json_node_new (JSON_NODE_VALUE);
json_node_set_value (node, &value);
g_value_unset (&value);
break;
case JSON_TOKEN_NULL:
node = json_node_new (JSON_NODE_NULL);
break;
default:
return G_TOKEN_RIGHT_BRACE;
}
if (node)
{
json_array_add_element (array, node);
node->parent = priv->current_node;
}
token = g_scanner_get_next_token (scanner);
}
json_node_take_array (priv->current_node, array);
return G_TOKEN_NONE;
}
static guint
json_parse_object (JsonParser *parser,
GScanner *scanner,
gboolean nested)
{
JsonParserPrivate *priv = parser->priv;
JsonObject *object;
guint token;
if (!nested)
{
/* the caller already swallowed the opening '{' */
token = g_scanner_get_next_token (scanner);
if (token != G_TOKEN_LEFT_CURLY)
return G_TOKEN_LEFT_CURLY;
}
object = json_object_new ();
token = g_scanner_get_next_token (scanner);
while (token != G_TOKEN_RIGHT_CURLY)
{
JsonNode *node = NULL;
gchar *name = NULL;
GValue value = { 0, };
if (token == G_TOKEN_COMMA)
{
/* swallow the comma */
token = g_scanner_get_next_token (scanner);
continue;
}
if (token == G_TOKEN_STRING)
{
name = g_strdup (scanner->value.v_string);
token = g_scanner_get_next_token (scanner);
if (token != ':')
{
g_free (name);
json_object_unref (object);
return ':';
}
else
{
/* swallow the colon */
token = g_scanner_get_next_token (scanner);
}
}
if (!name)
{
json_object_unref (object);
return G_TOKEN_STRING;
}
if (token == G_TOKEN_LEFT_CURLY)
{
JsonNode *old_node = priv->current_node;
priv->current_node = json_node_new (JSON_NODE_OBJECT);
token = json_parse_object (parser, scanner, TRUE);
node = priv->current_node;
priv->current_node = old_node;
if (token != G_TOKEN_NONE)
{
g_free (name);
json_node_free (node);
json_object_unref (object);
return token;
}
json_object_add_member (object, name, node);
node->parent = priv->current_node;
g_free (name);
token = g_scanner_get_next_token (scanner);
if (token == G_TOKEN_RIGHT_CURLY)
break;
continue;
}
if (token == G_TOKEN_LEFT_BRACE)
{
JsonNode *old_node = priv->current_node;
priv->current_node = json_node_new (JSON_NODE_ARRAY);
token = json_parse_array (parser, scanner, TRUE);
node = priv->current_node;
priv->current_node = old_node;
if (token != G_TOKEN_NONE)
{
g_free (name);
json_node_free (node);
json_object_unref (object);
return token;
}
json_object_add_member (object, name, node);
node->parent = priv->current_node;
g_free (name);
token = g_scanner_get_next_token (scanner);
if (token == G_TOKEN_RIGHT_BRACE)
break;
continue;
}
switch (token)
{
case G_TOKEN_INT:
g_value_init (&value, G_TYPE_INT);
g_value_set_int (&value, scanner->value.v_int);
node = json_node_new (JSON_NODE_VALUE);
json_node_set_value (node, &value);
g_value_unset (&value);
break;
case G_TOKEN_FLOAT:
g_value_init (&value, G_TYPE_FLOAT);
g_value_set_float (&value, scanner->value.v_float);
node = json_node_new (JSON_NODE_VALUE);
json_node_set_value (node, &value);
g_value_unset (&value);
break;
case G_TOKEN_STRING:
g_value_init (&value, G_TYPE_STRING);
g_value_set_string (&value, scanner->value.v_string);
node = json_node_new (JSON_NODE_VALUE);
json_node_set_value (node, &value);
g_value_unset (&value);
break;
case JSON_TOKEN_TRUE:
case JSON_TOKEN_FALSE:
g_value_init (&value, G_TYPE_BOOLEAN);
g_value_set_boolean (&value, token == JSON_TOKEN_TRUE ? TRUE : FALSE);
node = json_node_new (JSON_NODE_VALUE);
json_node_set_value (node, &value);
g_value_unset (&value);
break;
case JSON_TOKEN_NULL:
node = json_node_new (JSON_NODE_NULL);
break;
default:
return G_TOKEN_RIGHT_BRACE;
}
if (node)
{
json_object_add_member (object, name, node);
node->parent = priv->current_node;
}
g_free (name);
token = g_scanner_get_next_token (scanner);
}
json_node_take_object (priv->current_node, object);
return G_TOKEN_NONE;
}
static guint
json_parse_statement (JsonParser *parser,
GScanner *scanner)
{
JsonParserPrivate *priv = parser->priv;
guint token;
token = g_scanner_peek_next_token (scanner);
switch (token)
{
case G_TOKEN_LEFT_CURLY:
priv->root = priv->current_node = json_node_new (JSON_NODE_OBJECT);
return json_parse_object (parser, scanner, FALSE);
case G_TOKEN_LEFT_BRACE:
priv->root = priv->current_node = json_node_new (JSON_NODE_ARRAY);
return json_parse_array (parser, scanner, FALSE);
case JSON_TOKEN_NULL:
priv->root = priv->current_node = json_node_new (JSON_NODE_NULL);
return G_TOKEN_NONE;
default:
g_scanner_get_next_token (scanner);
return G_TOKEN_SYMBOL;
}
}
static void
json_scanner_msg_handler (GScanner *scanner,
gchar *message,
gboolean error)
{
JsonParser *parser = scanner->user_data;
if (error)
{
GError *error = NULL;
g_warning ("Line %d: %s", scanner->line, message);
g_set_error (&error, JSON_PARSER_ERROR,
JSON_PARSER_ERROR_PARSE,
"Parse error on line %d: %s",
scanner->line,
message);
g_signal_emit (parser, parser_signals[ERROR], 0, error);
g_error_free (error);
}
else
{
g_warning ("Line %d: %s", scanner->line, message);
}
}
static GScanner *
json_scanner_new (JsonParser *parser)
{
GScanner *scanner;
scanner = g_scanner_new (&json_scanner_config);
scanner->msg_handler = json_scanner_msg_handler;
scanner->user_data = parser;
return scanner;
}
/**
* json_parser_new:
*
* Creates a new #JsonParser instance. You can use the #JsonParser to
* load a JSON stream from either a file or a buffer and then walk the
* hierarchy using the data types API.
*
* Return value: the newly created #JsonParser. Use g_object_unref()
* to release all the memory it allocates.
*/
JsonParser *
json_parser_new (void)
{
return g_object_new (JSON_TYPE_PARSER, NULL);
}
/**
* json_parser_load_from_file:
* @parser: a #JsonParser
* @filename: the path for the file to parse
* @error: return location for a #GError, or %NULL
*
* Loads a JSON stream from the content of @filename and parses it. See
* json_parser_load_from_data().
*
* Return value: %TRUE if the file was successfully loaded and parsed.
* In case of error, @error is set accordingly and %FALSE is returned
*/
gboolean
json_parser_load_from_file (JsonParser *parser,
const gchar *filename,
GError **error)
{
GError *internal_error;
gchar *data;
gsize length;
gboolean retval = TRUE;
g_return_val_if_fail (JSON_IS_PARSER (parser), FALSE);
g_return_val_if_fail (filename != NULL, FALSE);
internal_error = NULL;
if (!g_file_get_contents (filename, &data, &length, &internal_error))
{
g_propagate_error (error, internal_error);
return FALSE;
}
if (!json_parser_load_from_data (parser, data, length, &internal_error))
{
g_propagate_error (error, internal_error);
retval = FALSE;
}
g_free (data);
return retval;
}
/**
* json_parser_load_from_data:
* @parser: a #JsonParser
* @data: the buffer to parse
* @length: the length of the buffer, or -1
* @error: return location for a #GError, or %NULL
*
* Loads a JSON stream from a buffer and parses it. You can call this function
* multiple times with the same #JsonParser object, but the contents of the
* parser will be destroyed each time.
*
* Return value: %TRUE if the buffer was succesfully parser. In case
* of error, @error is set accordingly and %FALSE is returned
*/
gboolean
json_parser_load_from_data (JsonParser *parser,
const gchar *data,
gsize length,
GError **error)
{
GScanner *scanner;
gboolean done;
gboolean retval = TRUE;
gint i;
g_return_val_if_fail (JSON_IS_PARSER (parser), FALSE);
g_return_val_if_fail (data != NULL, FALSE);
if (length < 0)
length = strlen (data);
if (parser->priv->root)
{
json_node_free (parser->priv->root);
parser->priv->root = NULL;
}
scanner = json_scanner_new (parser);
g_scanner_input_text (scanner, data, strlen (data));
for (i = 0; i < n_symbols; i++)
{
g_scanner_scope_add_symbol (scanner, 0,
symbol_names + symbols[i].name_offset,
GINT_TO_POINTER (symbols[i].token));
}
done = FALSE;
while (!done)
{
if (g_scanner_peek_next_token (scanner) == G_TOKEN_EOF)
done = TRUE;
else
{
guint expected_token;
expected_token = json_parse_statement (parser, scanner);
if (expected_token != G_TOKEN_NONE)
{
const gchar *symbol_name;
gchar *msg;
msg = NULL;
symbol_name = NULL;
if (scanner->scope_id == 0)
{
if (expected_token > JSON_TOKEN_INVALID &&
expected_token < JSON_TOKEN_LAST)
{
for (i = 0; i < n_symbols; i++)
if (symbols[i].token == expected_token)
msg = (gchar *) symbol_names + symbols[i].name_offset;
if (msg)
msg = g_strconcat ("e.g. `", msg, "'", NULL);
}
if (scanner->token > JSON_TOKEN_INVALID &&
scanner->token < JSON_TOKEN_LAST)
{
symbol_name = "???";
for (i = 0; i < n_symbols; i++)
if (symbols[i].token == scanner->token)
symbol_name = symbol_names + symbols[i].name_offset;
}
}
/* this will emit the ::error signal via the custom
* message handler we install
*/
g_scanner_unexp_token (scanner, expected_token,
NULL, "keyword",
symbol_name, msg,
TRUE);
/* we set a generic error here; the message from
* GScanner is relayed in the ::error signal
*/
g_set_error (error, JSON_PARSER_ERROR,
JSON_PARSER_ERROR_PARSE,
"Invalid token `%s' found: expecting %s",
symbol_name ? symbol_name : "???",
msg ? msg : "unknown");
retval = FALSE;
g_free (msg);
done = TRUE;
}
}
}
g_scanner_destroy (scanner);
parser->priv->current_node = NULL;
return retval;
}
/**
* json_parser_get_root:
* @parser: a #JsonParser
*
* Retrieves the top level node from the parsed JSON stream.
*
* Return value: the root #JsonNode . The returned node is owned by
* the #JsonParser and should never be modified or freed.
*/
JsonNode *
json_parser_get_root (JsonParser *parser)
{
g_return_val_if_fail (JSON_IS_PARSER (parser), NULL);
return parser->priv->root;
}
|