Implementation of xml_to_json(xml, indent)
function.
xml_to_json(xml, indent)
takes two arguments:
- xml - XML string UTF-8 encoded
- indent - Indent for pretty printed JSON or -1 for minified JSON
The input XML is not validated prior to conversion.
To compile with Emscripten as a WebAssembly function:
emcc -Oz xml_to_json.c -o xml_to_json.js -s EXPORTED_FUNCTIONS='["_xml_to_json", "_free"]' -s 'EXTRA_EXPORTED_RUNTIME_METHODS=["allocate", "intArrayFromString", "ALLOC_NORMAL", "UTF8ToString"]'
var xml = allocate(intArrayFromString("<x>hello world</x>"), 'i8', ALLOC_NORMAL);
var indent = 2;
var json = _xml_to_json(xml, indent);
console.log(UTF8ToString(json, 5000));
_free(xml);
_free(json);
{
"x": "hello world"
}
Implementation of an SQLite3 xml_to_json(X, N)
function.
xml_to_json(X, N)
takes one or two arguments:
- X - XML string UTF-8 encoded
- N - Optional indent for pretty printed JSON or -1 for minified JSON
The input XML is not validated prior to conversion.
To compile with gcc as a run-time loadable extension:
UNIX-like : gcc -g -O3 -fPIC -shared xml_to_json.c -o xml_to_json.so -DSQLITE
Mac : gcc -g -O3 -fPIC -dynamiclib xml_to_json.c -o xml_to_json.dylib -DSQLITE
Windows : gcc -g -O3 -shared xml_to_json.c -o xml_to_json.dll -DSQLITE
Add the -DDEBUG
option to print debug information to stdout.
E.g.
gcc -g -O3 -fPIC -shared xml_to_json.c -o xml_to_json.so -DDEBUG
SELECT xml_to_json('<x>hello world</x>', 2);
{
"x": "hello world"
}
SELECT xml_to_json('<x>a<y/>b</x>', 2);
{
"x": {
"#text": [
"a",
"b"
],
"y": null
}
}
SELECT xml_to_json('<x><y>abc</y><y>def</y></x>', 2);
{
"x": {
"y": [
"abc",
"def"
]
}
}
SELECT xml_to_json('<x>hello<y>abc</y>world<y>def</y>xyz</x>', 2);
{
"x": {
"#text": [
"hello",
"world",
"xyz"
],
"y": [
"abc",
"def"
]
}
}
SELECT xml_to_json('<x attr1="attr val 1" attr2="attr val 2">& > < '</x>', 2);
{
"x": {
"@attr1": "attr val 1",
"@attr2": "attr val 2",
"#text": "& > < '"
}
}
This implementation does not support the full XML 1.0 Specification. The following explaination is designed to describe what is currently supported.
TODO
- Improve readme
- Add test cases
- Benchmark