Converts XML to JSON and vice-versa using node-expat parser
npx @tessl/cli install tessl/npm-xml2json@0.12.0xml2json is a JavaScript library for converting between XML and JSON formats. It uses the node-expat parser for fast and reliable XML processing, supporting bidirectional conversion with comprehensive configuration options for both directions.
npm install xml2jsonconst parser = require('xml2json');For ES modules:
import parser from 'xml2json';const parser = require('xml2json');
// XML to JSON conversion
const xml = '<person name="John" age="30"><city>New York</city></person>';
const json = parser.toJson(xml);
console.log(json);
// Output: {"person":{"name":"John","age":"30","city":"New York"}}
// JSON to XML conversion
const xmlBack = parser.toXml(json);
console.log(xmlBack);
// Output: <person name="John" age="30"><city>New York</city></person>
// Return JavaScript object instead of JSON string
const obj = parser.toJson(xml, { object: true });
console.log(obj.person.name); // "John"
console.log(obj.person.city); // "New York"Converts XML strings or buffers to JSON format with extensive configuration options.
/**
* Converts XML to JSON string or JavaScript object
* @param {String|Buffer} xml - XML string or buffer to convert
* @param {Object} options - Configuration options for conversion
* @returns {String|Object} JSON string or JavaScript object
*/
function toJson(xml, options);Parameters:
xml (String|Buffer): XML content to convertoptions (Object, optional): Configuration optionsReturns: String (JSON) or Object (if options.object is true)
Usage Examples:
// Basic conversion
const json = parser.toJson('<root><item>value</item></root>');
// Return JavaScript object
const obj = parser.toJson(xml, { object: true });
// Enable type coercion for numbers and booleans
const typed = parser.toJson('<data><count>42</count><active>true</active></data>', {
object: true,
coerce: true
});
// Result: { data: { count: 42, active: true } }
// Force array notation for consistent structure
const arrays = parser.toJson('<list><item>a</item><item>b</item></list>', {
object: true,
arrayNotation: true
});
// Custom text node property
const custom = parser.toJson('<tag>text content</tag>', {
object: true,
alternateTextNode: 'text'
});Converts JSON strings or JavaScript objects to XML format.
/**
* Converts JSON to XML string
* @param {String|Object} json - JSON string or JavaScript object to convert
* @param {Object} options - Configuration options for conversion
* @returns {String} XML string
*/
function toXml(json, options);Parameters:
json (String|Object): JSON string or JavaScript object to convertoptions (Object, optional): Configuration optionsReturns: String (XML)
Usage Examples:
// Basic conversion
const xml = parser.toXml('{"person":{"name":"John","age":"30"}}');
// From JavaScript object
const xml2 = parser.toXml({ person: { name: "John", age: "30" } });
// With sanitization enabled
const xml3 = parser.toXml({ message: "Hello <world> & friends" }, {
sanitize: true
});
// Ignore null values
const xml4 = parser.toXml({ data: { value: "test", empty: null } }, {
ignoreNull: true
});CLI tool for converting XML to JSON from stdin to stdout.
# Convert XML file to JSON
cat file.xml | xml2json
# Check version
xml2json --versionThe CLI reads XML from standard input and outputs JSON to standard output.
interface ToJsonOptions {
/** Return JavaScript object instead of JSON string */
object?: boolean;
/** Generate reversible JSON with $t text nodes */
reversible?: boolean;
/** Enable type coercion for numbers/booleans or provide custom coercion */
coerce?: boolean | Record<string, (value: string) => any>;
/** Sanitize special XML characters in values */
sanitize?: boolean;
/** Trim whitespace from element values */
trim?: boolean;
/** Force array notation for all elements or specific element names */
arrayNotation?: boolean | string[];
/** Change default $t text node property name */
alternateTextNode?: boolean | string;
}Default values:
{
object: false,
reversible: false,
coerce: false,
sanitize: true,
trim: true,
arrayNotation: false,
alternateTextNode: false
}Option Details:
object - When true, returns a JavaScript object instead of a JSON stringreversible - When true, generates reversible JSON with $t text node properties for exact XML reconstructioncoerce - When true, converts string values to numbers or booleans. Can be an object with custom coercion functions keyed by element/attribute namessanitize - When true (default), escapes XML special characters: &, <, > in element values; &, <, >, ", ' in attribute valuestrim - When true (default), removes leading and trailing whitespace from element valuesarrayNotation - When true, treats all child elements as arrays. When an array of strings, only specified element names are treated as arraysalternateTextNode - When true, uses _t instead of $t for text nodes. When a string, uses that string as the text node property nameinterface ToXmlOptions {
/** Sanitize values when converting to XML */
sanitize?: boolean;
/** Ignore null values during conversion */
ignoreNull?: boolean;
}Default values:
{
sanitize: false,
ignoreNull: false
}Option Details:
sanitize - When true, sanitizes values during JSON to XML conversion (default false for backward compatibility)ignoreNull - When true, skips null values during conversionThe library throws errors in the following cases:
toXml)try {
const result = parser.toJson('<invalid><xml>');
} catch (error) {
console.error('XML parsing error:', error.message);
}
try {
const result = parser.toXml('invalid json string');
} catch (error) {
console.error('JSON parsing error:', error.message);
}/** Main parser object with conversion functions */
interface Parser {
toJson(xml: string | Buffer, options?: ToJsonOptions): string | object;
toXml(json: string | object, options?: ToXmlOptions): string;
}
/** Configuration options for XML to JSON conversion */
interface ToJsonOptions {
object?: boolean;
reversible?: boolean;
coerce?: boolean | Record<string, (value: string) => any>;
sanitize?: boolean;
trim?: boolean;
arrayNotation?: boolean | string[];
alternateTextNode?: boolean | string;
}
/** Configuration options for JSON to XML conversion */
interface ToXmlOptions {
sanitize?: boolean;
ignoreNull?: boolean;
}xml2json uses special properties to represent XML text content:
$t propertyreversible: true, all text content uses $t to ensure exact XML reconstructionalternateTextNode to customize the text property name// Default text handling
const result = parser.toJson('<tag>Hello World</tag>', { object: true });
// Result: { tag: { $t: "Hello World" } }
// Custom text node property
const custom = parser.toJson('<tag>Hello World</tag>', {
object: true,
alternateTextNode: 'text'
});
// Result: { tag: { text: "Hello World" } }
// Mixed content with attributes
const mixed = parser.toJson('<person name="John">Hello</person>', { object: true });
// Result: { person: { name: "John", $t: "Hello" } }The library does not parse the following XML elements:
These elements are either ignored or converted to JSON without preserving their XML-specific semantics.