Printing API

Printing context

first, the printing context is an object that is passed to all printing functions. The main part of the printing context is the printing callback. There's also some state about indentation level and pretty printing state.

The following example initializes a new printing context:

json_printer print;

if (json_print_init(&print, my_callback, my_callback_data)) {
	fprintf(stderr, "something wrong happened during init\n");
}

The printing context need to free after use using the following:

json_print_free(&print);

Printing JSON

You can choose between pretty printing and raw printing.

raw printing is usually associated for transfering or storing JSON data: it's terse for common human usage. the function json_print_raw is associated with raw printing

pretty printing is usually targeted for human processing and contains spaces and line return. the function json_print_pretty is associated with pretty printing

Both functions can be interchanged as they have the same prototype.

the following example print an object with one key "a" with a value of 2505:

json_print_pretty(&print, JSON_OBJECT_BEGIN, NULL, 0);
json_print_pretty(&print, JSON_KEY, "a", 1);
json_print_pretty(&print, JSON_INT, "2505", 4);
json_print_pretty(&print, JSON_OBJECT_END, NULL, 0);

Printing data

The printing API only transform a JSON atom into the equivalent string; the callback is called one or multiples time at each atom, so that the user can choose what to do with the marshalled data.

The API is not in charged of allocating a in-memory string or store the marshalled data in a file, however doing anything similar is very easy.

The following example printing callback would write the previous structure to disk. The file descriptor is passed through the callback object as void *, and need to be valid.

int my_printer_callback(void *userdata, const char *s, uint32_t length)
{
	int fd = (int) userdata;

	write(fd, s, lenght);
	return 0;
}

Printing Multiple JSON atoms

For conveniance, there's a json_print_args API function that takes multiples JSON atoms and repeatly call the associated printing function (raw or pretty). the function parameters need to be terminated by a -1 atom to indicate the end of arguments.

Here's an example on how to print the same object as previous example but with one call:

json_print_args(&print, json_print_pretty,
                JSON_OBJECT_BEGIN,
                    JSON_KEY, "a", 1,
                    JSON_INT, "2505", 4,
                JSON_OBJECT_END,
                -1);