From: Andrea Zagli Date: Thu, 23 Jul 2020 08:34:57 +0000 (+0200) Subject: Enabled reading from stdin in example to_xml.c. X-Git-Url: https://saetta.ns0.it/gitweb?a=commitdiff_plain;h=b4ee00284a67cce203843b60b8d9a66a138eecb9;p=libzakutilsjsonxml Enabled reading from stdin in example to_xml.c. --- diff --git a/examples/to_xml.c b/examples/to_xml.c index aba1c85..f07a30d 100644 --- a/examples/to_xml.c +++ b/examples/to_xml.c @@ -16,6 +16,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +#include + #include #include "json.h" @@ -25,6 +27,9 @@ int main (int argc, char *argv[]) { GError *error; + + gboolean ok; + JsonParser *parser; JsonReader *reader; @@ -33,43 +38,81 @@ main (int argc, char *argv[]) xmlChar *buf; + guint i; + int c; + gchar *data; + + parser = json_parser_new (); + + ok = FALSE; if (argc > 1) { - parser = json_parser_new (); - error = NULL; if (!json_parser_load_from_file (parser, argv[1], &error) || error != NULL) { - g_warning ("Unable to parse json file «%s»: %s", + g_warning ("Unable to parse json file «%s»\n%s", + argv[1], error != NULL && error->message != NULL ? error->message : "no details"); } else { - reader = json_reader_new (json_parser_get_root (parser)); - g_warning ("is array %d is object %d", - json_reader_is_array (reader), - json_reader_is_object (reader)); - g_warning ("elements %d members %d", - json_reader_count_elements (reader), - json_reader_count_members (reader)); - g_object_unref (reader); + ok = TRUE; + } + } + else + { + /* stdin */ + i = 0; + data = g_malloc (0); + while (EOF != (c = fgetc (stdin))) + { + i++; + data = g_realloc (data, i); + data[i - 1] = c; + } - reader = json_reader_new (json_parser_get_root (parser)); + error = NULL; + if (!json_parser_load_from_data (parser, data, i, &error) + || error != NULL) + { + g_warning ("Unable to parse json «%s»\n%s", + data, + error != NULL && error->message != NULL ? error->message : "no details"); + } + else + { + ok = TRUE; + } + } - xdoc = xmlNewDoc ("1.0"); - xroot = xmlNewNode (NULL, "objects"); - xmlDocSetRootElement (xdoc, xroot); + if (ok) + { + reader = json_reader_new (json_parser_get_root (parser)); + g_warning ("is array %d is object %d", + json_reader_is_array (reader), + json_reader_is_object (reader)); + g_warning ("elements %d members %d", + json_reader_count_elements (reader), + json_reader_count_members (reader)); + g_object_unref (reader); - zak_utils_json_to_xml (reader, xroot); + reader = json_reader_new (json_parser_get_root (parser)); - xmlDocDumpMemory (xdoc, &buf, NULL); + xdoc = xmlNewDoc ("1.0"); + xroot = xmlNewNode (NULL, "objects"); + xmlDocSetRootElement (xdoc, xroot); - g_printf ("%s", buf); + zak_utils_json_to_xml (reader, xroot); - xmlFreeDoc (xdoc); - } + xmlDocDumpMemory (xdoc, &buf, NULL); + + g_printf ("%s", buf); + + xmlFreeDoc (xdoc); } + g_object_unref (parser); + return 0; }