Skip to content

Instantly share code, notes, and snippets.

@octo
Created August 9, 2010 21:04
Show Gist options
  • Save octo/516112 to your computer and use it in GitHub Desktop.
Save octo/516112 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <yajl/yajl_tree.h>
static int print_value (yajl_value_t *v, int indent);
static int print_object (yajl_value_object_t *o, int indent)
{
size_t i;
printf ("\n%*s\n", indent + 1, "{");
for (i = 0; i < o->children_num; i++)
{
if (i > 0)
printf (",\n");
printf ("%*s", indent, "");
print_value (o->keys[i], indent + 2);
printf (": ");
print_value (o->values[i], indent + 2);
}
printf ("\n%*s", indent + 1, "}");
}
static int print_array (yajl_value_array_t *a, int indent)
{
size_t i;
printf ("\n%*s\n", indent + 1, "[");
for (i = 0; i < a->children_num; i++)
{
if (i > 0)
printf (",\n");
printf ("%*s", indent + 2, "");
print_value (a->children[i], indent + 2);
}
printf ("\n%*s", indent + 1, "]");
}
static int print_value (yajl_value_t *v, int indent)
{
if (v == NULL)
return (EINVAL);
if (v->type == VALUE_TYPE_STRING)
printf ("\"%s\"", v->data.string.value);
else if (v->type == VALUE_TYPE_OBJECT)
return (print_object (&v->data.object, indent));
else if (v->type == VALUE_TYPE_ARRAY)
return (print_array (&v->data.array, indent));
else
printf ("\n=== unknown type %#"PRIx8" ===\n", v->type);
return (0);
}
int main (int argc, char **argv)
{
char *buffer = NULL;
size_t buffer_size = 0;
yajl_value_t *v;
while (42)
{
char tmp[4096];
ssize_t status;
char *ptr;
status = read (STDIN_FILENO, tmp, sizeof (tmp));
if (status < 0)
{
if ((errno == EAGAIN) || (errno == EINTR))
continue;
perror ("read");
abort ();
}
else if (status == 0)
break;
printf ("status = %zi;\n", status);
ptr = realloc (buffer, buffer_size + ((size_t) status) + 1);
if (ptr == NULL)
{
perror ("realloc");
abort ();
}
buffer = ptr;
memcpy (buffer + buffer_size, tmp, (size_t) status);
buffer_size += status;
buffer[buffer_size] = 0;
} /* while (42) */
printf ("Finished reading %zu bytes from STDIN.\n", buffer_size);
v = yajl_tree_parse (buffer);
printf ("yajl_tree_parse returned %p.\n", (void *) v);
print_value (v, 0);
printf ("\n");
fflush (stdout);
yajl_tree_free (v);
exit (EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment