1 /* json-parser.c - JSON streams parser
3 * This file is part of JSON-GLib
5 * Copyright © 2007, 2008, 2009 OpenedHand Ltd
6 * Copyright © 2009, 2010 Intel Corp.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
22 * Emmanuele Bassi <ebassi@linux.intel.com>
27 * @short_description: Parse JSON data streams
29 * #JsonParser provides an object for parsing a JSON data stream, either
30 * inside a file or inside a static buffer.
37 #include <glib/gi18n-lib.h>
39 #include "json-types-private.h"
41 #include "json-debug.h"
42 #include "json-marshal.h"
43 #include "json-parser.h"
44 #include "json-scanner.h"
46 struct _JsonParserPrivate
49 JsonNode *current_node;
53 JsonParserError error_code;
59 guint has_assignment : 1;
60 guint is_filename : 1;
63 static const gchar symbol_names[] =
74 { 0, JSON_TOKEN_TRUE },
75 { 5, JSON_TOKEN_FALSE },
76 { 11, JSON_TOKEN_NULL },
77 { 16, JSON_TOKEN_VAR }
80 static const guint n_symbols = G_N_ELEMENTS (symbols);
97 static guint parser_signals[LAST_SIGNAL] = { 0, };
99 G_DEFINE_QUARK (json-parser-error-quark, json_parser_error)
101 G_DEFINE_TYPE_WITH_PRIVATE (JsonParser, json_parser, G_TYPE_OBJECT)
103 static guint json_parse_array (JsonParser *parser,
104 JsonScanner *scanner,
106 static guint json_parse_object (JsonParser *parser,
107 JsonScanner *scanner,
111 json_parser_clear (JsonParser *parser)
113 JsonParserPrivate *priv = parser->priv;
115 g_free (priv->variable_name);
116 priv->variable_name = NULL;
118 if (priv->last_error)
120 g_error_free (priv->last_error);
121 priv->last_error = NULL;
126 json_node_free (priv->root);
132 json_parser_dispose (GObject *gobject)
134 json_parser_clear (JSON_PARSER (gobject));
136 G_OBJECT_CLASS (json_parser_parent_class)->dispose (gobject);
140 json_parser_finalize (GObject *gobject)
142 JsonParserPrivate *priv = JSON_PARSER (gobject)->priv;
144 g_free (priv->variable_name);
145 g_free (priv->filename);
147 G_OBJECT_CLASS (json_parser_parent_class)->finalize (gobject);
151 json_parser_class_init (JsonParserClass *klass)
153 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
155 gobject_class->dispose = json_parser_dispose;
156 gobject_class->finalize = json_parser_finalize;
159 * JsonParser::parse-start:
160 * @parser: the #JsonParser that received the signal
162 * The ::parse-start signal is emitted when the parser began parsing
163 * a JSON data stream.
165 parser_signals[PARSE_START] =
166 g_signal_new ("parse-start",
167 G_OBJECT_CLASS_TYPE (gobject_class),
169 G_STRUCT_OFFSET (JsonParserClass, parse_start),
171 _json_marshal_VOID__VOID,
174 * JsonParser::parse-end:
175 * @parser: the #JsonParser that received the signal
177 * The ::parse-end signal is emitted when the parser successfully
178 * finished parsing a JSON data stream
180 parser_signals[PARSE_END] =
181 g_signal_new ("parse-end",
182 G_OBJECT_CLASS_TYPE (gobject_class),
184 G_STRUCT_OFFSET (JsonParserClass, parse_end),
186 _json_marshal_VOID__VOID,
189 * JsonParser::object-start:
190 * @parser: the #JsonParser that received the signal
192 * The ::object-start signal is emitted each time the #JsonParser
193 * starts parsing a #JsonObject.
195 parser_signals[OBJECT_START] =
196 g_signal_new ("object-start",
197 G_OBJECT_CLASS_TYPE (gobject_class),
199 G_STRUCT_OFFSET (JsonParserClass, object_start),
201 _json_marshal_VOID__VOID,
204 * JsonParser::object-member:
205 * @parser: the #JsonParser that received the signal
206 * @object: a #JsonObject
207 * @member_name: the name of the newly parsed member
209 * The ::object-member signal is emitted each time the #JsonParser
210 * has successfully parsed a single member of a #JsonObject. The
211 * object and member are passed to the signal handlers.
213 parser_signals[OBJECT_MEMBER] =
214 g_signal_new ("object-member",
215 G_OBJECT_CLASS_TYPE (gobject_class),
217 G_STRUCT_OFFSET (JsonParserClass, object_member),
219 _json_marshal_VOID__BOXED_STRING,
224 * JsonParser::object-end:
225 * @parser: the #JsonParser that received the signal
226 * @object: the parsed #JsonObject
228 * The ::object-end signal is emitted each time the #JsonParser
229 * has successfully parsed an entire #JsonObject.
231 parser_signals[OBJECT_END] =
232 g_signal_new ("object-end",
233 G_OBJECT_CLASS_TYPE (gobject_class),
235 G_STRUCT_OFFSET (JsonParserClass, object_end),
237 _json_marshal_VOID__BOXED,
241 * JsonParser::array-start:
242 * @parser: the #JsonParser that received the signal
244 * The ::array-start signal is emitted each time the #JsonParser
245 * starts parsing a #JsonArray
247 parser_signals[ARRAY_START] =
248 g_signal_new ("array-start",
249 G_OBJECT_CLASS_TYPE (gobject_class),
251 G_STRUCT_OFFSET (JsonParserClass, array_start),
253 _json_marshal_VOID__VOID,
256 * JsonParser::array-element:
257 * @parser: the #JsonParser that received the signal
258 * @array: a #JsonArray
259 * @index_: the index of the newly parsed element
261 * The ::array-element signal is emitted each time the #JsonParser
262 * has successfully parsed a single element of a #JsonArray. The
263 * array and element index are passed to the signal handlers.
265 parser_signals[ARRAY_ELEMENT] =
266 g_signal_new ("array-element",
267 G_OBJECT_CLASS_TYPE (gobject_class),
269 G_STRUCT_OFFSET (JsonParserClass, array_element),
271 _json_marshal_VOID__BOXED_INT,
276 * JsonParser::array-end:
277 * @parser: the #JsonParser that received the signal
278 * @array: the parsed #JsonArray
280 * The ::array-end signal is emitted each time the #JsonParser
281 * has successfully parsed an entire #JsonArray
283 parser_signals[ARRAY_END] =
284 g_signal_new ("array-end",
285 G_OBJECT_CLASS_TYPE (gobject_class),
287 G_STRUCT_OFFSET (JsonParserClass, array_end),
289 _json_marshal_VOID__BOXED,
294 * @parser: the parser instance that received the signal
295 * @error: a pointer to the #GError
297 * The ::error signal is emitted each time a #JsonParser encounters
298 * an error in a JSON stream.
300 parser_signals[ERROR] =
301 g_signal_new ("error",
302 G_OBJECT_CLASS_TYPE (gobject_class),
304 G_STRUCT_OFFSET (JsonParserClass, error),
306 _json_marshal_VOID__POINTER,
312 json_parser_init (JsonParser *parser)
314 JsonParserPrivate *priv = json_parser_get_instance_private (parser);
319 priv->current_node = NULL;
321 priv->error_code = JSON_PARSER_ERROR_PARSE;
322 priv->last_error = NULL;
324 priv->has_assignment = FALSE;
325 priv->variable_name = NULL;
327 priv->is_filename = FALSE;
328 priv->filename = FALSE;
332 json_parse_value (JsonParser *parser,
333 JsonScanner *scanner,
337 JsonParserPrivate *priv = parser->priv;
338 JsonNode *current_node = priv->current_node;
339 gboolean is_negative = FALSE;
343 guint next_token = json_scanner_peek_next_token (scanner);
345 if (next_token == G_TOKEN_INT ||
346 next_token == G_TOKEN_FLOAT)
349 token = json_scanner_get_next_token (scanner);
358 JSON_NOTE (PARSER, "abs(node): %" G_GINT64_FORMAT " (sign: %s)",
359 scanner->value.v_int64,
360 is_negative ? "negative" : "positive");
361 *node = json_node_init_int (json_node_alloc (),
362 is_negative ? scanner->value.v_int64 * -1
363 : scanner->value.v_int64);
367 JSON_NOTE (PARSER, "abs(node): %.6f (sign: %s)",
368 scanner->value.v_float,
369 is_negative ? "negative" : "positive");
370 *node = json_node_init_double (json_node_alloc (),
371 is_negative ? scanner->value.v_float * -1.0
372 : scanner->value.v_float);
376 JSON_NOTE (PARSER, "node: '%s'",
377 scanner->value.v_string);
378 *node = json_node_init_string (json_node_alloc (), scanner->value.v_string);
381 case JSON_TOKEN_TRUE:
382 case JSON_TOKEN_FALSE:
383 JSON_NOTE (PARSER, "node: '%s'",
384 JSON_TOKEN_TRUE ? "<true>" : "<false>");
385 *node = json_node_init_boolean (json_node_alloc (), token == JSON_TOKEN_TRUE ? TRUE : FALSE);
388 case JSON_TOKEN_NULL:
389 JSON_NOTE (PARSER, "node: <null>");
390 *node = json_node_init_null (json_node_alloc ());
393 case G_TOKEN_IDENTIFIER:
394 JSON_NOTE (PARSER, "node: identifier '%s'", scanner->value.v_identifier);
395 priv->error_code = JSON_PARSER_ERROR_INVALID_BAREWORD;
397 return G_TOKEN_SYMBOL;
401 JsonNodeType cur_type;
405 JSON_NOTE (PARSER, "node: invalid token");
407 cur_type = json_node_get_node_type (current_node);
408 if (cur_type == JSON_NODE_ARRAY)
410 priv->error_code = JSON_PARSER_ERROR_PARSE;
411 return G_TOKEN_RIGHT_BRACE;
413 else if (cur_type == JSON_NODE_OBJECT)
415 priv->error_code = JSON_PARSER_ERROR_PARSE;
416 return G_TOKEN_RIGHT_CURLY;
420 priv->error_code = JSON_PARSER_ERROR_INVALID_BAREWORD;
421 return G_TOKEN_SYMBOL;
431 json_parse_array (JsonParser *parser,
432 JsonScanner *scanner,
435 JsonParserPrivate *priv = parser->priv;
436 JsonNode *old_current;
441 old_current = priv->current_node;
442 priv->current_node = json_node_init_array (json_node_alloc (), NULL);
444 array = json_array_new ();
446 token = json_scanner_get_next_token (scanner);
447 g_assert (token == G_TOKEN_LEFT_BRACE);
449 g_signal_emit (parser, parser_signals[ARRAY_START], 0);
452 while (token != G_TOKEN_RIGHT_BRACE)
454 guint next_token = json_scanner_peek_next_token (scanner);
455 JsonNode *element = NULL;
457 /* parse the element */
460 case G_TOKEN_LEFT_BRACE:
461 JSON_NOTE (PARSER, "Nested array at index %d", idx);
462 token = json_parse_array (parser, scanner, &element);
465 case G_TOKEN_LEFT_CURLY:
466 JSON_NOTE (PARSER, "Nested object at index %d", idx);
467 token = json_parse_object (parser, scanner, &element);
470 case G_TOKEN_RIGHT_BRACE:
474 token = json_scanner_get_next_token (scanner);
475 token = json_parse_value (parser, scanner, token, &element);
479 if (token != G_TOKEN_NONE || element == NULL)
481 /* the json_parse_* functions will have set the error code */
482 json_array_unref (array);
483 json_node_free (priv->current_node);
484 priv->current_node = old_current;
489 next_token = json_scanner_peek_next_token (scanner);
491 if (next_token == G_TOKEN_COMMA)
493 token = json_scanner_get_next_token (scanner);
494 next_token = json_scanner_peek_next_token (scanner);
496 /* look for trailing commas */
497 if (next_token == G_TOKEN_RIGHT_BRACE)
499 priv->error_code = JSON_PARSER_ERROR_TRAILING_COMMA;
501 json_array_unref (array);
502 json_node_free (priv->current_node);
503 json_node_free (element);
504 priv->current_node = old_current;
506 return G_TOKEN_RIGHT_BRACE;
510 JSON_NOTE (PARSER, "Array element %d completed", idx + 1);
511 json_node_set_parent (element, priv->current_node);
512 json_array_add_element (array, element);
514 g_signal_emit (parser, parser_signals[ARRAY_ELEMENT], 0,
522 json_scanner_get_next_token (scanner);
524 json_node_take_array (priv->current_node, array);
525 json_node_set_parent (priv->current_node, old_current);
527 g_signal_emit (parser, parser_signals[ARRAY_END], 0, array);
529 if (node != NULL && *node == NULL)
530 *node = priv->current_node;
532 priv->current_node = old_current;
538 json_parse_object (JsonParser *parser,
539 JsonScanner *scanner,
542 JsonParserPrivate *priv = parser->priv;
544 JsonNode *old_current;
547 old_current = priv->current_node;
548 priv->current_node = json_node_init_object (json_node_alloc (), NULL);
550 object = json_object_new ();
552 token = json_scanner_get_next_token (scanner);
553 g_assert (token == G_TOKEN_LEFT_CURLY);
555 g_signal_emit (parser, parser_signals[OBJECT_START], 0);
557 while (token != G_TOKEN_RIGHT_CURLY)
559 guint next_token = json_scanner_peek_next_token (scanner);
560 JsonNode *member = NULL;
563 /* we need to abort here because empty objects do not
566 if (next_token == G_TOKEN_RIGHT_CURLY)
569 /* parse the member's name */
570 if (next_token != G_TOKEN_STRING)
572 JSON_NOTE (PARSER, "Missing object member name");
574 priv->error_code = JSON_PARSER_ERROR_INVALID_BAREWORD;
576 json_object_unref (object);
577 json_node_free (priv->current_node);
578 priv->current_node = old_current;
580 return G_TOKEN_STRING;
584 token = json_scanner_get_next_token (scanner);
585 name = g_strdup (scanner->value.v_string);
586 if (name == NULL || *name == '\0')
588 JSON_NOTE (PARSER, "Empty object member name");
590 priv->error_code = JSON_PARSER_ERROR_EMPTY_MEMBER_NAME;
592 json_object_unref (object);
593 json_node_free (priv->current_node);
594 priv->current_node = old_current;
596 return G_TOKEN_STRING;
599 JSON_NOTE (PARSER, "Object member '%s'", name);
601 /* a colon separates names from values */
602 next_token = json_scanner_peek_next_token (scanner);
603 if (next_token != ':')
605 JSON_NOTE (PARSER, "Missing object member name separator");
607 priv->error_code = JSON_PARSER_ERROR_MISSING_COLON;
610 json_object_unref (object);
611 json_node_free (priv->current_node);
612 priv->current_node = old_current;
617 /* we swallow the ':' */
618 token = json_scanner_get_next_token (scanner);
619 g_assert (token == ':');
620 next_token = json_scanner_peek_next_token (scanner);
622 /* parse the member's value */
625 case G_TOKEN_LEFT_BRACE:
626 JSON_NOTE (PARSER, "Nested array at member %s", name);
627 token = json_parse_array (parser, scanner, &member);
630 case G_TOKEN_LEFT_CURLY:
631 JSON_NOTE (PARSER, "Nested object at member %s", name);
632 token = json_parse_object (parser, scanner, &member);
636 /* once a member name is defined we need a value */
637 token = json_scanner_get_next_token (scanner);
638 token = json_parse_value (parser, scanner, token, &member);
642 if (token != G_TOKEN_NONE || member == NULL)
644 /* the json_parse_* functions will have set the error code */
646 json_object_unref (object);
647 json_node_free (priv->current_node);
648 priv->current_node = old_current;
653 next_token = json_scanner_peek_next_token (scanner);
654 if (next_token == G_TOKEN_COMMA)
656 token = json_scanner_get_next_token (scanner);
657 next_token = json_scanner_peek_next_token (scanner);
659 /* look for trailing commas */
660 if (next_token == G_TOKEN_RIGHT_CURLY)
662 priv->error_code = JSON_PARSER_ERROR_TRAILING_COMMA;
664 json_object_unref (object);
665 json_node_free (member);
666 json_node_free (priv->current_node);
667 priv->current_node = old_current;
669 return G_TOKEN_RIGHT_BRACE;
672 else if (next_token == G_TOKEN_STRING)
674 priv->error_code = JSON_PARSER_ERROR_MISSING_COMMA;
676 json_object_unref (object);
677 json_node_free (member);
678 json_node_free (priv->current_node);
679 priv->current_node = old_current;
681 return G_TOKEN_COMMA;
684 JSON_NOTE (PARSER, "Object member '%s' completed", name);
685 json_node_set_parent (member, priv->current_node);
686 json_object_set_member (object, name, member);
688 g_signal_emit (parser, parser_signals[OBJECT_MEMBER], 0,
697 json_scanner_get_next_token (scanner);
699 json_node_take_object (priv->current_node, object);
700 json_node_set_parent (priv->current_node, old_current);
702 g_signal_emit (parser, parser_signals[OBJECT_END], 0, object);
704 if (node != NULL && *node == NULL)
705 *node = priv->current_node;
707 priv->current_node = old_current;
713 json_parse_statement (JsonParser *parser,
714 JsonScanner *scanner)
716 JsonParserPrivate *priv = parser->priv;
719 token = json_scanner_peek_next_token (scanner);
722 case G_TOKEN_LEFT_CURLY:
723 JSON_NOTE (PARSER, "Statement is object declaration");
724 return json_parse_object (parser, scanner, &priv->root);
726 case G_TOKEN_LEFT_BRACE:
727 JSON_NOTE (PARSER, "Statement is array declaration");
728 return json_parse_array (parser, scanner, &priv->root);
730 /* some web APIs are not only passing the data structures: they are
731 * also passing an assigment, which makes parsing horribly complicated
732 * only because web developers are lazy, and writing "var foo = " is
733 * evidently too much to request from them.
740 JSON_NOTE (PARSER, "Statement is an assignment");
742 /* swallow the 'var' token... */
743 token = json_scanner_get_next_token (scanner);
745 /* ... swallow the variable name... */
746 next_token = json_scanner_get_next_token (scanner);
747 if (next_token != G_TOKEN_IDENTIFIER)
749 priv->error_code = JSON_PARSER_ERROR_INVALID_BAREWORD;
750 return G_TOKEN_IDENTIFIER;
753 name = g_strdup (scanner->value.v_identifier);
755 /* ... and finally swallow the '=' */
756 next_token = json_scanner_get_next_token (scanner);
757 if (next_token != '=')
759 priv->error_code = JSON_PARSER_ERROR_INVALID_BAREWORD;
764 priv->has_assignment = TRUE;
765 priv->variable_name = name;
767 token = json_parse_statement (parser, scanner);
769 /* remove the trailing semi-colon */
770 next_token = json_scanner_peek_next_token (scanner);
771 if (next_token == ';')
773 token = json_scanner_get_next_token (scanner);
781 case JSON_TOKEN_NULL:
782 case JSON_TOKEN_TRUE:
783 case JSON_TOKEN_FALSE:
788 case G_TOKEN_IDENTIFIER:
789 JSON_NOTE (PARSER, "Statement is a value");
790 token = json_scanner_get_next_token (scanner);
791 return json_parse_value (parser, scanner, token, &priv->root);
794 JSON_NOTE (PARSER, "Unknown statement");
795 json_scanner_get_next_token (scanner);
796 priv->error_code = JSON_PARSER_ERROR_INVALID_BAREWORD;
797 return G_TOKEN_SYMBOL;
802 json_scanner_msg_handler (JsonScanner *scanner,
805 JsonParser *parser = scanner->user_data;
806 JsonParserPrivate *priv = parser->priv;
807 GError *error = NULL;
809 /* translators: %s: is the file name, the first %d is the line
810 * number, the second %d is the position on the line, and %s is
813 g_set_error (&error, JSON_PARSER_ERROR,
815 _("%s:%d:%d: Parse error: %s"),
816 priv->is_filename ? priv->filename : "<data>",
821 parser->priv->last_error = error;
822 g_signal_emit (parser, parser_signals[ERROR], 0, error);
826 json_scanner_create (JsonParser *parser)
828 JsonScanner *scanner;
831 scanner = json_scanner_new ();
832 scanner->msg_handler = json_scanner_msg_handler;
833 scanner->user_data = parser;
835 /* XXX: this is eminently stupid, but we use the symbols later on, so
836 * we cannot move them into JsonScanner without moving a bunch of code
839 for (i = 0; i < n_symbols; i++)
841 json_scanner_scope_add_symbol (scanner, 0,
842 symbol_names + symbols[i].name_offset,
843 GINT_TO_POINTER (symbols[i].token));
852 * Creates a new #JsonParser instance. You can use the #JsonParser to
853 * load a JSON stream from either a file or a buffer and then walk the
854 * hierarchy using the data types API.
856 * Return value: the newly created #JsonParser. Use g_object_unref()
857 * to release all the memory it allocates.
860 json_parser_new (void)
862 return g_object_new (JSON_TYPE_PARSER, NULL);
866 json_parser_load (JsonParser *parser,
871 JsonParserPrivate *priv = parser->priv;
872 JsonScanner *scanner;
874 gboolean retval = TRUE;
877 json_parser_clear (parser);
879 if (!g_utf8_validate (data, length, NULL))
881 g_set_error_literal (error, JSON_PARSER_ERROR,
882 JSON_PARSER_ERROR_INVALID_DATA,
883 _("JSON data must be UTF-8 encoded"));
884 g_signal_emit (parser, parser_signals[ERROR], 0, *error);
888 scanner = json_scanner_create (parser);
889 json_scanner_input_text (scanner, data, length);
891 priv->scanner = scanner;
893 g_signal_emit (parser, parser_signals[PARSE_START], 0);
898 if (json_scanner_peek_next_token (scanner) == G_TOKEN_EOF)
902 guint expected_token;
905 /* we try to show the expected token, if possible */
906 expected_token = json_parse_statement (parser, scanner);
907 if (expected_token != G_TOKEN_NONE)
909 const gchar *symbol_name;
912 cur_token = scanner->token;
916 if (scanner->scope_id == 0)
918 if (expected_token > JSON_TOKEN_INVALID &&
919 expected_token < JSON_TOKEN_LAST)
921 for (i = 0; i < n_symbols; i++)
922 if (symbols[i].token == expected_token)
923 symbol_name = symbol_names + symbols[i].name_offset;
926 msg = g_strconcat ("e.g. '", symbol_name, "'", NULL);
929 if (cur_token > JSON_TOKEN_INVALID &&
930 cur_token < JSON_TOKEN_LAST)
934 for (i = 0; i < n_symbols; i++)
935 if (symbols[i].token == cur_token)
936 symbol_name = symbol_names + symbols[i].name_offset;
940 /* this will emit the ::error signal via the custom
941 * message handler we install
943 json_scanner_unexp_token (scanner, expected_token,
947 /* and this will propagate the error we create in the
948 * same message handler
950 if (priv->last_error)
952 g_propagate_error (error, priv->last_error);
953 priv->last_error = NULL;
964 g_signal_emit (parser, parser_signals[PARSE_END], 0);
966 /* remove the scanner */
967 json_scanner_destroy (scanner);
968 priv->scanner = NULL;
969 priv->current_node = NULL;
975 * json_parser_load_from_file:
976 * @parser: a #JsonParser
977 * @filename: the path for the file to parse
978 * @error: return location for a #GError, or %NULL
980 * Loads a JSON stream from the content of @filename and parses it. See
981 * json_parser_load_from_data().
983 * Return value: %TRUE if the file was successfully loaded and parsed.
984 * In case of error, @error is set accordingly and %FALSE is returned
987 json_parser_load_from_file (JsonParser *parser,
988 const gchar *filename,
991 JsonParserPrivate *priv;
992 GError *internal_error;
995 gboolean retval = TRUE;
997 g_return_val_if_fail (JSON_IS_PARSER (parser), FALSE);
998 g_return_val_if_fail (filename != NULL, FALSE);
1000 priv = parser->priv;
1002 internal_error = NULL;
1003 if (!g_file_get_contents (filename, &data, &length, &internal_error))
1005 g_propagate_error (error, internal_error);
1009 g_free (priv->filename);
1011 priv->is_filename = TRUE;
1012 priv->filename = g_strdup (filename);
1014 if (!json_parser_load (parser, data, length, &internal_error))
1016 g_propagate_error (error, internal_error);
1026 * json_parser_load_from_data:
1027 * @parser: a #JsonParser
1028 * @data: the buffer to parse
1029 * @length: the length of the buffer, or -1
1030 * @error: return location for a #GError, or %NULL
1032 * Loads a JSON stream from a buffer and parses it. You can call this function
1033 * multiple times with the same #JsonParser object, but the contents of the
1034 * parser will be destroyed each time.
1036 * Return value: %TRUE if the buffer was succesfully parser. In case
1037 * of error, @error is set accordingly and %FALSE is returned
1040 json_parser_load_from_data (JsonParser *parser,
1045 JsonParserPrivate *priv;
1046 GError *internal_error;
1047 gboolean retval = TRUE;
1049 g_return_val_if_fail (JSON_IS_PARSER (parser), FALSE);
1050 g_return_val_if_fail (data != NULL, FALSE);
1052 priv = parser->priv;
1055 length = strlen (data);
1057 priv->is_filename = FALSE;
1058 g_free (priv->filename);
1059 priv->filename = NULL;
1061 internal_error = NULL;
1062 if (!json_parser_load (parser, data, length, &internal_error))
1064 g_propagate_error (error, internal_error);
1072 * json_parser_get_root:
1073 * @parser: a #JsonParser
1075 * Retrieves the top level node from the parsed JSON stream.
1077 * Return value: (transfer none): the root #JsonNode . The returned
1078 * node is owned by the #JsonParser and should never be modified
1082 json_parser_get_root (JsonParser *parser)
1084 g_return_val_if_fail (JSON_IS_PARSER (parser), NULL);
1086 return parser->priv->root;
1090 * json_parser_get_current_line:
1091 * @parser: a #JsonParser
1093 * Retrieves the line currently parsed, starting from 1.
1095 * This function has defined behaviour only while parsing; calling this
1096 * function from outside the signal handlers emitted by #JsonParser will
1099 * Return value: the currently parsed line, or 0.
1102 json_parser_get_current_line (JsonParser *parser)
1104 g_return_val_if_fail (JSON_IS_PARSER (parser), 0);
1106 if (parser->priv->scanner != NULL)
1107 return parser->priv->scanner->line;
1113 * json_parser_get_current_pos:
1114 * @parser: a #JsonParser
1116 * Retrieves the current position inside the current line, starting
1119 * This function has defined behaviour only while parsing; calling this
1120 * function from outside the signal handlers emitted by #JsonParser will
1123 * Return value: the position in the current line, or 0.
1126 json_parser_get_current_pos (JsonParser *parser)
1128 g_return_val_if_fail (JSON_IS_PARSER (parser), 0);
1130 if (parser->priv->scanner != NULL)
1131 return parser->priv->scanner->position;
1137 * json_parser_has_assignment:
1138 * @parser: a #JsonParser
1139 * @variable_name: (out) (allow-none) (transfer none): Return location for the variable
1142 * A JSON data stream might sometimes contain an assignment, like:
1145 * var _json_data = { "member_name" : [ ...
1148 * even though it would technically constitute a violation of the RFC.
1150 * #JsonParser will ignore the left hand identifier and parse the right
1151 * hand value of the assignment. #JsonParser will record, though, the
1152 * existence of the assignment in the data stream and the variable name
1155 * Return value: %TRUE if there was an assignment, %FALSE otherwise. If
1156 * @variable_name is not %NULL it will be set to the name of the variable
1157 * used in the assignment. The string is owned by #JsonParser and should
1158 * never be modified or freed.
1163 json_parser_has_assignment (JsonParser *parser,
1164 gchar **variable_name)
1166 JsonParserPrivate *priv;
1168 g_return_val_if_fail (JSON_IS_PARSER (parser), FALSE);
1170 priv = parser->priv;
1172 if (priv->has_assignment && variable_name)
1173 *variable_name = priv->variable_name;
1175 return priv->has_assignment;
1178 #define GET_DATA_BLOCK_SIZE 8192
1181 * json_parser_load_from_stream:
1182 * @parser: a #JsonParser
1183 * @stream: an open #GInputStream
1184 * @cancellable: (allow-none): a #GCancellable, or %NULL
1185 * @error: the return location for a #GError, or %NULL
1187 * Loads the contents of an input stream and parses them.
1189 * If @cancellable is not %NULL, then the operation can be cancelled by
1190 * triggering the @cancellable object from another thread. If the
1191 * operation was cancelled, the error %G_IO_ERROR_CANCELLED will be set
1192 * on the passed @error.
1194 * Return value: %TRUE if the data stream was successfully read and
1195 * parsed, and %FALSE otherwise
1200 json_parser_load_from_stream (JsonParser *parser,
1201 GInputStream *stream,
1202 GCancellable *cancellable,
1205 GByteArray *content;
1208 gboolean retval = FALSE;
1209 GError *internal_error;
1211 g_return_val_if_fail (JSON_IS_PARSER (parser), FALSE);
1212 g_return_val_if_fail (G_IS_INPUT_STREAM (stream), FALSE);
1213 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1215 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1218 content = g_byte_array_new ();
1221 g_byte_array_set_size (content, pos + GET_DATA_BLOCK_SIZE + 1);
1222 while ((res = g_input_stream_read (stream, content->data + pos,
1223 GET_DATA_BLOCK_SIZE,
1224 cancellable, error)) > 0)
1227 g_byte_array_set_size (content, pos + GET_DATA_BLOCK_SIZE + 1);
1232 /* error has already been set */
1237 /* zero-terminate the content; we allocated an extra byte for this */
1238 content->data[pos] = 0;
1240 internal_error = NULL;
1241 retval = json_parser_load (parser, (const gchar *) content->data, pos, &internal_error);
1243 if (internal_error != NULL)
1244 g_propagate_error (error, internal_error);
1247 g_byte_array_free (content, TRUE);
1252 typedef struct _LoadStreamData
1256 GCancellable *cancellable;
1257 GAsyncReadyCallback callback;
1259 GByteArray *content;
1264 load_stream_data_free (gpointer data)
1266 LoadStreamData *closure;
1268 if (G_UNLIKELY (data == NULL))
1274 g_error_free (closure->error);
1276 if (closure->cancellable)
1277 g_object_unref (closure->cancellable);
1279 if (closure->content)
1280 g_byte_array_free (closure->content, TRUE);
1282 g_object_unref (closure->parser);
1288 load_stream_data_read_callback (GObject *object,
1289 GAsyncResult *read_res,
1292 GInputStream *stream = G_INPUT_STREAM (object);
1293 LoadStreamData *data = user_data;
1294 GError *error = NULL;
1297 read_size = g_input_stream_read_finish (stream, read_res, &error);
1301 data->error = error;
1304 GSimpleAsyncResult *res;
1307 res = g_simple_async_result_new (G_OBJECT (data->parser),
1310 json_parser_load_from_stream_async);
1311 g_simple_async_result_set_op_res_gpointer (res, data, load_stream_data_free);
1312 g_simple_async_result_complete (res);
1313 g_object_unref (res);
1316 else if (read_size > 0)
1318 data->pos += read_size;
1320 g_byte_array_set_size (data->content, data->pos + GET_DATA_BLOCK_SIZE);
1322 g_input_stream_read_async (stream, data->content->data + data->pos,
1323 GET_DATA_BLOCK_SIZE,
1326 load_stream_data_read_callback,
1331 GSimpleAsyncResult *res;
1333 res = g_simple_async_result_new (G_OBJECT (data->parser),
1336 json_parser_load_from_stream_async);
1337 g_simple_async_result_set_op_res_gpointer (res, data, load_stream_data_free);
1338 g_simple_async_result_complete (res);
1339 g_object_unref (res);
1344 * json_parser_load_from_stream_finish:
1345 * @parser: a #JsonParser
1346 * @result: a #GAsyncResult
1347 * @error: the return location for a #GError or %NULL
1349 * Finishes an asynchronous stream loading started with
1350 * json_parser_load_from_stream_async().
1352 * Return value: %TRUE if the content of the stream was successfully retrieves
1353 * and parsed, and %FALSE otherwise. In case of error, the #GError will be
1354 * filled accordingly.
1359 json_parser_load_from_stream_finish (JsonParser *parser,
1360 GAsyncResult *result,
1363 GSimpleAsyncResult *simple;
1364 GError *internal_error;
1365 LoadStreamData *data;
1368 g_return_val_if_fail (JSON_IS_PARSER (parser), FALSE);
1369 g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);
1371 simple = G_SIMPLE_ASYNC_RESULT (result);
1373 if (g_simple_async_result_propagate_error (simple, error))
1376 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == json_parser_load_from_stream_async);
1378 data = g_simple_async_result_get_op_res_gpointer (simple);
1382 g_propagate_error (error, data->error);
1387 g_byte_array_set_size (data->content, data->pos + 1);
1388 data->content->data[data->pos] = 0;
1390 internal_error = NULL;
1391 res = json_parser_load (parser, (const gchar *) data->content->data, data->pos, &internal_error);
1393 if (internal_error != NULL)
1394 g_propagate_error (error, internal_error);
1400 * json_parser_load_from_stream_async:
1401 * @parser: a #JsonParser
1402 * @stream: a #GInputStream
1403 * @cancellable: (allow-none): a #GCancellable, or %NULL
1404 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
1405 * @user_data: the data to pass to @callback
1407 * Asynchronously reads the contents of @stream.
1409 * For more details, see json_parser_load_from_stream() which is the
1410 * synchronous version of this call.
1412 * When the operation is finished, @callback will be called. You should
1413 * then call json_parser_load_from_stream_finish() to get the result
1419 json_parser_load_from_stream_async (JsonParser *parser,
1420 GInputStream *stream,
1421 GCancellable *cancellable,
1422 GAsyncReadyCallback callback,
1425 LoadStreamData *data;
1427 g_return_if_fail (JSON_IS_PARSER (parser));
1428 g_return_if_fail (G_IS_INPUT_STREAM (stream));
1429 g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1431 data = g_new0 (LoadStreamData, 1);
1433 if (cancellable != NULL)
1434 data->cancellable = g_object_ref (cancellable);
1436 data->callback = callback;
1437 data->user_data = user_data;
1438 data->content = g_byte_array_new ();
1439 data->parser = g_object_ref (parser);
1441 g_byte_array_set_size (data->content, data->pos + GET_DATA_BLOCK_SIZE);
1442 g_input_stream_read_async (stream, data->content->data + data->pos,
1443 GET_DATA_BLOCK_SIZE, 0,
1445 load_stream_data_read_callback,