a firstworks project
Rudiments
About Documentation Download Licensing News

Using the jsondom class

The jsondom class provides a framework for DOM parsing of JSON data. It parses a file or string of JSON-formatted data and produces a dom tree representing the data. Like the xmldom class, the tree can be navigated using the domnode class. Since the jsondom class creates a representation of the JSON data in memory, it should not be used to process arbitrarily large documents which could exhaust system memory.

The dom tree uses an "r" element for the root, named elements for each object or array, and "v" elements for each array value. Each element has a "t" attribute indicating the type: "o" for object, "a" for array, "s" for string, "n" for number, "t" for true, "f" for false, and "u" for null. String and number elements also have a "v" attribute containing the value.

The following program parses a JSON string containing a list of animals, walks the tree to print each animal's name, type, number of legs, and whether it is domestic, and writes the dom tree to standard output.

#include <rudiments/jsondom.h>
#include <rudiments/domnode.h>
#include <rudiments/charstring.h>
#include <rudiments/stdio.h>

int main(int argc, const char **argv) {

	jsondom	json;

	// parse a json string
	json.parseString(
		"{"
		"  \"animals\": ["
		"    {"
		"      \"name\": \"dog\","
		"      \"type\": \"mammal\","
		"      \"legs\": 4,"
		"      \"domestic\": true"
		"    },"
		"    {"
		"      \"name\": \"eagle\","
		"      \"type\": \"bird\","
		"      \"legs\": 2,"
		"      \"domestic\": false"
		"    },"
		"    {"
		"      \"name\": \"snake\","
		"      \"type\": \"reptile\","
		"      \"legs\": 0,"
		"      \"domestic\": false"
		"    }"
		"  ]"
		"}");


	// walk the tree
	// the dom tree structure is:
	//   r (root) -> animals (array) -> v (value) -> name, type, legs, ...
	domnode	*root=json.getRootNode();
	domnode	*animals=root->getFirstTagChild()->
				getFirstTagChild("animals");

	stdoutput.write("all animals:\n");
	for (domnode *v=animals->getFirstTagChild("v");
			!v->isNullNode();
			v=v->getNextTagSibling("v")) {

		const char	*name=v->getFirstTagChild("name")->
						getAttributeValue("v");
		const char	*type=v->getFirstTagChild("type")->
						getAttributeValue("v");
		const char	*legs=v->getFirstTagChild("legs")->
						getAttributeValue("v");
		const char	*domestictype=
			v->getFirstTagChild("domestic")->
						getAttributeValue("t");
		const char	*domestic=
			(!charstring::compare(domestictype,"t"))?
							"yes":"no";

		stdoutput.printf("  %s (%s) - %s legs - domestic: %s\n",
						name,type,legs,domestic);
	}
	stdoutput.write('\n');


	// write the dom tree to standard output
	stdoutput.write("dom output:\n");
	json.write(true);
}
Copyright 2017 - David Muse - Contact