DOM parsing helper

For convenience, there's some helpers function that permits constructing JSON DOM tree. they are built on top of the event based parsing API described earlier.

DOM parsing context

a DOM parsing context hold the state of the DOM building. it also hold 3 differents callbacks to create the JSON values in the tree.

the first callback, create_structure, is called when a new object or array is suppose to be created. the callback can choose the representation of the data, but need to returns a single void * to represent this new structure.

the second callback, create_data, is called for each value that is not an object or an array. it need returning a void * to represent this value.

the last callback, append, is called each time we need to append a value to an existing structure (array/object). if called with a non-NULL key, then the first argument of the function represent an object, otherwise an array.

the following example hook into a hypothetical framework with array and object special method:

void *tree_create_structure(int nesting, int is_object)
	if (is_object)
		return new_object();
		return new_array();

void *tree_create_data(int type, const char *data, uint32_t length)
	switch (type) {
	case JSON_INT:
		return new_json_value(type, data, length);
	case JSON_NULL:
	case JSON_TRUE:
		return new_json_const(type);

int tree_append(void *structure, char *key, uint32_t key_length, void *obj)
	if (key != NULL) {
		my_object *object = structure;
		append_object(object, key, key_length, obj);
	} else {
		my_array *array = structure;
		append_array(array, obj);

Hooking into the event parser

the following example hooks the DOM helper parser into the event parser:

json_parser_dom helper;
json_parser parser;

json_parser_dom_init(&helper, create_structure, create_data, append);
json_parser_init(&parser, json_parser_dom_callback, &helper);