junit2json
Version:
Convert JUnit XML format to JSON
77 lines • 2.56 kB
JavaScript
import { parseStringPromise, processors } from 'xml2js';
/**
* Parses the given JUnit XML string into a JavaScript object representation using xml2js library.
*
* @example Basic usage
* ```ts
* import { parse } from 'junit2json'
*
* const junitXmlString = "..."
* const output = await parse(xmlString)
* ```
*
* If you want to filter some tags like `<system-out>` or `<system-err>`, you can use `replacer` function argument in [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify).
*
* @example Filter some tags
* ```ts
* import { parse } from 'junit2json'
*
* const junitXmlString = "..."
* const output = await parse(xmlString)
* const replacer = (key: any, value: any) => {
* if (key === 'system-out' || key === 'system-err') return undefined
* return value
* }
* console.log(JSON.stringify(output, replacer, 2))
* ```
*/
export const parse = async (xmlString, xml2jsOptions) => {
const options = xml2jsOptions ?? {
attrValueProcessors: [processors.parseNumbers]
};
const result = await parseStringPromise(xmlString, options);
if (result === null)
return null;
if ('testsuites' in result) {
return _parse(result['testsuites']);
}
else if ('testsuite' in result) {
return _parse(result['testsuite']);
}
};
const _parse = (objOrArray) => {
if (Array.isArray(objOrArray)) {
return objOrArray.map((_obj) => {
// Do recursive call when _obj is nested array OR object that key is "$"
if (Array.isArray(_obj) || typeof (_obj) === 'object') {
return _parse(_obj);
}
// Return object that has only "inner" field when _obj is String
return { inner: _obj };
});
}
let output = {};
Object.keys(objOrArray).forEach((key) => {
const nested = objOrArray[key];
if (key === '$') {
output = { ...output, ..._parse(nested) };
}
else if (key === 'system-out' || key === 'system-err') {
output[key] = nested.map((inner) => inner);
}
else if (key === 'properties') {
output[key] = _parse(nested[0]?.property || []);
}
else if (typeof (nested) === 'object') {
output[key] = _parse(nested);
}
else if (key === '_') {
output['inner'] = nested;
}
else {
output[key] = nested;
}
});
return output;
};
//# sourceMappingURL=index.js.map