or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-xml2json

Converts XML to JSON and vice-versa using node-expat parser

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/xml2json@0.12.x

To install, run

npx @tessl/cli install tessl/npm-xml2json@0.12.0

index.mddocs/

xml2json

xml2json 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.

Package Information

  • Package Name: xml2json
  • Package Type: npm
  • Language: JavaScript (Node.js)
  • Installation: npm install xml2json

Core Imports

const parser = require('xml2json');

For ES modules:

import parser from 'xml2json';

Basic Usage

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"

Capabilities

XML to JSON Conversion

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 convert
  • options (Object, optional): Configuration options

Returns: 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'
});

JSON to XML Conversion

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 convert
  • options (Object, optional): Configuration options

Returns: 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
});

Command Line Interface

CLI tool for converting XML to JSON from stdin to stdout.

# Convert XML file to JSON
cat file.xml | xml2json

# Check version
xml2json --version

The CLI reads XML from standard input and outputs JSON to standard output.

Configuration Options

toJson Options

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 string
  • reversible - When true, generates reversible JSON with $t text node properties for exact XML reconstruction
  • coerce - When true, converts string values to numbers or booleans. Can be an object with custom coercion functions keyed by element/attribute names
  • sanitize - When true (default), escapes XML special characters: &, <, > in element values; &, <, >, ", ' in attribute values
  • trim - When true (default), removes leading and trailing whitespace from element values
  • arrayNotation - When true, treats all child elements as arrays. When an array of strings, only specified element names are treated as arrays
  • alternateTextNode - When true, uses _t instead of $t for text nodes. When a string, uses that string as the text node property name

toXml Options

interface 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 conversion

Error Handling

The library throws errors in the following cases:

  • Invalid XML: When the XML structure is malformed or cannot be parsed by node-expat
  • Invalid JSON: When the JSON string cannot be parsed (for toXml)
  • Invalid Options: When provided options don't match the expected schema (validated using joi)
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);
}

Types

/** 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;
}

Text Node Handling

xml2json uses special properties to represent XML text content:

  • Default: Text content is stored in the $t property
  • Reversible mode: When reversible: true, all text content uses $t to ensure exact XML reconstruction
  • Custom text nodes: Use alternateTextNode 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" } }

Limitations

The library does not parse the following XML elements:

  • CDATA sections (content is converted but structure is not reversible)
  • Processing instructions
  • XML declarations
  • Entity declarations
  • Comments

These elements are either ignored or converted to JSON without preserving their XML-specific semantics.