npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

softlogistic-json-to-xml-adapter-2.0.0

v2.0.0

Published

A robust Node.js library that converts between JSON/JavaScript objects and XML strings using xml-js with comprehensive error handling, validation, and formatting options - supports bidirectional conversion (JSON ↔ XML)

Readme

JSON ↔ XML Bidirectional Converter Library

A robust Node.js library that converts between JavaScript objects and XML strings using the xml-js library with comprehensive error handling and formatting options. Supports bidirectional conversion - JSON to XML and XML to JSON.

Features

  • ✅ Convert JavaScript objects to XML
  • ✅ Convert XML strings to JavaScript objects (NEW in 2.0.0)
  • ✅ Pretty printing with customizable indentation (both directions)
  • ✅ Compact output mode (both directions)
  • ✅ Comprehensive error handling
  • ✅ Strict validation mode
  • ✅ Custom root element naming
  • ✅ XML attribute support
  • ✅ Full round-trip conversion support (JSON→XML→JSON)
  • ✅ Well-documented API
  • ✅ Production-ready
  • ✅ TypeScript definitions included

Installation

npm install

This will install the xml-js dependency specified in package.json.

API Reference

Main Functions

jsonToXml(jsObject, options)

Converts a JavaScript object to XML string with flexible options.

Parameters:

  • jsObject (Object): The JavaScript object to convert
  • options (Object, optional):
    • prettyPrint (boolean): Format XML with indentation (default: true)
    • indentSize (number): Spaces for indentation (default: 2)
    • ignoreDeclaration (boolean): Omit XML declaration (default: false)
    • ignoreComment (boolean): Ignore comments (default: false)
    • rootName (string): Root element name if not in object (default: 'root')
    • compact (boolean): Use compact representation (default: false)

Returns: XML string

Throws: Error if input is invalid or conversion fails

Example:

const converter = require('./src/index');

const data = {
  name: 'John',
  age: 30
};

const xml = converter.jsonToXml(data, {
  prettyPrint: true,
  indentSize: 2
});

console.log(xml);

jsonToXmlPretty(jsObject, indentSize)

Convenience function for pretty-printed XML output.

Parameters:

  • jsObject (Object): The JavaScript object to convert
  • indentSize (number): Spaces for indentation (default: 2)

Returns: Formatted XML string

Example:

const person = { name: 'Alice', age: 28 };
const xml = converter.jsonToXmlPretty(person, 4);

jsonToXmlCompact(jsObject)

Creates compact XML without formatting.

Parameters:

  • jsObject (Object): The JavaScript object to convert

Returns: Compact XML string

Example:

const data = { name: 'Bob', email: '[email protected]' };
const xml = converter.jsonToXmlCompact(data);

jsonToXmlStrict(jsObject, options)

Converts with strict validation - throws errors for invalid inputs.

Parameters:

  • jsObject (Object): The JavaScript object to convert
  • options (Object, optional): Same as jsonToXml

Returns: XML string

Throws: Error for null, undefined, arrays at root, or non-objects

Example:

try {
  const xml = converter.jsonToXmlStrict(data);
} catch (error) {
  console.error('Validation error:', error.message);
}

Alias Methods

For convenience, the library also exports:

JSON to XML:

  • convert() - alias for jsonToXml()
  • convertPretty() - alias for jsonToXmlPretty()
  • convertCompact() - alias for jsonToXmlCompact()
  • convertStrict() - alias for jsonToXmlStrict()

XML to JSON (NEW in 2.0.0):

  • parseXml() - alias for xmlToJson()
  • parseXmlPretty() - alias for xmlToJsonPretty()
  • parseXmlCompact() - alias for xmlToJsonCompact()
  • parseXmlStrict() - alias for xmlToJsonStrict()

XML to JSON Conversion Functions

xmlToJson(xmlString, options)

Converts an XML string to a JavaScript object with flexible options.

Parameters:

  • xmlString (string): The XML string to convert
  • options (Object, optional):
    • prettyPrint (boolean): Format JSON output (default: false)
    • indentSize (number): Spaces for JSON indentation (default: 2)
    • ignoreDeclaration (boolean): Ignore XML declaration (default: true)
    • ignoreComment (boolean): Ignore XML comments (default: true)

Returns: JavaScript object

Throws: Error if XML parsing fails or string is empty

Example:

const converter = require('./src/index');

const xmlString = `<?xml version="1.0" encoding="utf-8"?>
<person>
  <name>John Doe</name>
  <age>30</age>
</person>`;

const json = converter.xmlToJson(xmlString);
console.log(json);
// Output: { person: { name: 'John Doe', age: '30' } }

xmlToJsonPretty(xmlString, indentSize)

Convenience function for pretty-printed JSON object output.

Parameters:

  • xmlString (string): The XML string to convert
  • indentSize (number): Spaces for indentation (default: 2)

Returns: Formatted JavaScript object

Example:

const json = converter.xmlToJsonPretty(xmlString, 4);
console.log(JSON.stringify(json, null, 4));

xmlToJsonCompact(xmlString)

Creates compact JSON object without formatting.

Parameters:

  • xmlString (string): The XML string to convert

Returns: Compact JavaScript object

Example:

const json = converter.xmlToJsonCompact(xmlString);

xmlToJsonStrict(xmlString, options)

Converts with strict validation - throws detailed errors for invalid XML.

Parameters:

  • xmlString (string): The XML string to convert
  • options (Object, optional): Same as xmlToJson

Returns: JavaScript object

Throws: Error for null, undefined, empty, or malformed XML

Example:

try {
  const json = converter.xmlToJsonStrict(xmlString);
} catch (error) {
  console.error('Parse error:', error.message);
}

---## Usage Examples

Simple Object

const converter = require('./src/index');

const person = {
  name: 'John Doe',
  age: 30,
  email: '[email protected]'
};

const xml = converter.jsonToXmlPretty(person);
console.log(xml);

/* Output:
<?xml version="1.0" encoding="utf-8"?>
<root>
  <name>John Doe</name>
  <age>30</age>
  <email>[email protected]</email>
</root>
*/

Nested Objects

const company = {
  company: {
    name: 'Tech Corp',
    location: {
      city: 'New York',
      country: 'USA'
    }
  }
};

const xml = converter.jsonToXmlPretty(company);

Arrays in Objects

const team = {
  team: {
    name: 'Development',
    members: {
      member: [
        { name: 'Alice', role: 'Lead' },
        { name: 'Bob', role: 'Developer' },
        { name: 'Carol', role: 'QA' }
      ]
    }
  }
};

const xml = converter.jsonToXmlPretty(team);

Custom Root Element

const data = {
  title: 'Sample',
  value: 42
};

const xml = converter.jsonToXml(data, {
  prettyPrint: true,
  rootName: 'customElement'
});

/* Output:
<?xml version="1.0" encoding="utf-8"?>
<customElement>
  <title>Sample</title>
  <value>42</value>
</customElement>
*/

Complex Structure

const order = {
  order: {
    orderId: 'ORD-001',
    customer: {
      name: 'John Smith',
      email: '[email protected]'
    },
    items: {
      item: [
        {
          id: 'P001',
          name: 'Product 1',
          quantity: 2,
          price: 29.99
        },
        {
          id: 'P002',
          name: 'Product 2',
          quantity: 1,
          price: 49.99
        }
      ]
    }
  }
};

const xml = converter.jsonToXmlPretty(order);

Error Handling

The library includes comprehensive error handling for both conversion directions:

const converter = require('./src/index');

// JSON to XML - Null input
try {
  converter.jsonToXml(null);
} catch (error) {
  console.error(error.message); // Input object cannot be null or undefined
}

// XML to JSON - Invalid XML
try {
  converter.xmlToJson('<invalid>');
} catch (error) {
  console.error(error.message); // XML parsing failed
}

// XML to JSON - Empty string
try {
  converter.xmlToJsonStrict('');
} catch (error) {
  console.error(error.message); // XML string cannot be empty
}

// Array at root level (strict mode)
try {
  converter.jsonToXmlStrict([1, 2, 3]);
} catch (error) {
  console.error(error.message); // Input cannot be an array at root level
}

Bidirectional Conversion Examples (NEW in 2.0.0)

JSON → XML → JSON Round Trip

const converter = require('./src/index');

// Start with JSON object
const originalData = {
  person: {
    name: 'Alice Smith',
    age: 28,
    email: '[email protected]'
  }
};

// Convert to XML
const xml = converter.jsonToXmlPretty(originalData);
console.log('Generated XML:');
console.log(xml);

// Convert back to JSON
const parsedData = converter.xmlToJsonPretty(xml);
console.log('\nParsed back to JSON:');
console.log(JSON.stringify(parsedData, null, 2));

// Note: Number types become strings in XML→JSON conversion
// { person: { name: 'Alice Smith', age: '28', email: '[email protected]' } }

Complex Nested Structure with Arrays

const converter = require('./src/index');

const data = {
  company: {
    name: 'TechCorp',
    employees: [
      { id: 1, name: 'Alice', role: 'Engineer' },
      { id: 2, name: 'Bob', role: 'Designer' }
    ]
  }
};

// Convert to XML
const xml = converter.jsonToXmlPretty(data);

// Convert back
const parsed = converter.xmlToJsonPretty(xml);
console.log(parsed);

Direct XML String Parsing

const converter = require('./src/index');

const xmlString = `<?xml version="1.0" encoding="utf-8"?>
<book>
  <title>The Great Gatsby</title>
  <author>F. Scott Fitzgerald</author>
  <year>1925</year>
  <pages>180</pages>
</book>`;

// Parse XML directly to JSON
const bookData = converter.xmlToJsonPretty(xmlString);
console.log(bookData);
// Output: { book: { title: '...', author: '...', year: '1925', pages: '180' } }

Options Reference

| Option | Type | Default | Description | |--------|------|---------|-------------| | prettyPrint | boolean | true | Format XML with indentation | | indentSize | number | 2 | Number of spaces per indentation level | | ignoreDeclaration | boolean | false | Omit XML declaration line | | ignoreComment | boolean | false | Ignore comment nodes | | rootName | string | 'root' | Name for root element if not provided | | compact | boolean | false | Use compact representation |

Running Examples

To run the example files and see all functions in action:

# Test basic JSON to XML conversion
npm test

# Test advanced utilities
npm run test:advanced

# Test full test suite with all examples
npm run test:suite

# Run bidirectional conversion examples
node examples/bidirectional-example.js

Or directly run individual example files:

node examples/example.js
node examples/advanced-example.js
node examples/bidirectional-example.js

Project Structure

json-to-xml-converter/
├── src/
│   ├── index.js          # Main entry point and exports
│   └── converter.js      # Core conversion logic and functions
├── examples/
│   └── example.js        # Usage examples and demonstrations
├── package.json          # Project metadata and dependencies
└── README.md             # This file

Dependencies

  • xml-js (^1.6.11): XML to JSON parser and generator

License

MIT

Contributing

Contributions are welcome! Feel free to:

  • Report bugs
  • Suggest improvements
  • Submit pull requests

Use Cases

This library is ideal for:

JSON to XML:

  • Converting JSON responses to XML format
  • Data transformation in middleware applications
  • API integration adapters
  • Configuration file generation
  • Data serialization for legacy systems
  • Creating XML documents from JavaScript objects

XML to JSON (NEW in 2.0.0):

  • Parsing XML documents into JavaScript objects
  • Converting legacy XML data to modern JSON format
  • Bidirectional API adapters
  • XML file processing and transformation
  • Data migration from XML to JSON systems
  • REST API request/response transformation

Bidirectional Use Cases:

  • Building universal data adapters
  • Creating middleware that works with both XML and JSON
  • Data format agnostic applications
  • Legacy system integration bridges
  • Full round-trip data synchronization

Performance Notes

  • The library uses the mature xml-js library for XML generation
  • Pretty printing adds minimal overhead
  • Suitable for production environments
  • No external dependencies beyond xml-js

Version: 2.0.0 (with Bidirectional Conversion)
Last Updated: February 2026