@naman22khater/data-converter
v1.0.1
Published
A universal data format converter with central engine architecture - supports JSON, XML, YAML conversions
Maintainers
Readme
@naman22khater/data-converter
A universal data format converter with a central engine architecture. Convert seamlessly between JSON, XML, and YAML formats.
Features
- 🔄 Universal Conversion - Convert between JSON, XML, and YAML
- 🏗️ Central Engine Architecture - Uses Intermediate Representation (IR) for efficient format conversion
- 📦 Zero Dependencies - Lightweight with no external dependencies
- 🎯 TypeScript Support - Full TypeScript definitions included
- 🌐 Multiple Builds - ESM, CommonJS, and UMD bundles available
- ⚡ Extensible - Easy to add new formats (only requires parser + serializer)
Installation
npm install @naman22khater/data-converterQuick Start
import { convert } from '@naman22khater/data-converter';
// JSON to XML
const xmlResult = convert('{"name": "John", "age": 30}', {
from: 'json',
to: 'xml'
});
console.log(xmlResult.output);
// <?xml version="1.0" encoding="UTF-8"?>
// <root>
// <name>John</name>
// <age>30</age>
// </root>
// XML to YAML
const yamlResult = convert('<user><name>John</name></user>', {
from: 'xml',
to: 'yaml'
});
console.log(yamlResult.output);
// user:
// name: John
// JSON to YAML
const yamlResult2 = convert('{"users": [{"name": "Alice"}, {"name": "Bob"}]}', {
from: 'json',
to: 'yaml'
});
console.log(yamlResult2.output);API Reference
convert(input, options)
Main conversion function.
const result = convert(input: string, {
from: 'json' | 'xml' | 'yaml',
to: 'json' | 'xml' | 'yaml',
parseOptions?: object, // Format-specific parse options
serializeOptions?: object // Format-specific serialize options
});
// Returns: { output: string, ir?: IRDocument }parse(input, format, options?)
Parse input into Intermediate Representation.
import { parse } from '@naman22khater/data-converter';
const ir = parse('{"name": "John"}', 'json');serialize(ir, format, options?)
Serialize IR to a specific format.
import { serialize } from '@naman22khater/data-converter';
const output = serialize(ir, 'xml', { indent: 4 });engine
Access the conversion engine directly for advanced use cases.
import { engine } from '@naman22khater/data-converter';
// Check supported formats
console.log(engine.getSupportedSourceFormats()); // ['json', 'xml', 'yaml']
// Check if conversion is possible
console.log(engine.canConvert('json', 'xml')); // true
// Register custom format handlers
engine.registerParser(myCustomParser);
engine.registerSerializer(myCustomSerializer);Serialization Options
XML Options
convert(json, {
from: 'json',
to: 'xml',
serializeOptions: {
declaration: true, // Include XML declaration (default: true)
indent: 2, // Indentation spaces (default: 2)
rootElement: 'root', // Root element name for objects/arrays
arrayItemName: 'item', // Element name for array items
attributePrefix: '@', // Prefix for attributes in JSON
textNodeName: '#text' // Key for text content in JSON
}
});JSON Options
convert(xml, {
from: 'xml',
to: 'json',
serializeOptions: {
indent: 2, // Indentation spaces (default: 2)
attributePrefix: '@', // Prefix for XML attributes
textNodeName: '#text' // Key for text content
}
});YAML Options
convert(json, {
from: 'json',
to: 'yaml',
serializeOptions: {
indent: 2, // Indentation spaces (default: 2)
quoteStrings: false // Force quote all strings
}
});Parse Options
XML Parse Options
convert(xml, {
from: 'xml',
to: 'json',
parseOptions: {
ignoreAttributes: false, // Skip XML attributes
ignoreComments: true, // Skip XML comments
trimText: true // Trim whitespace from text
}
});Architecture
This library uses a Central Engine with Intermediate Representation (IR) architecture:
Source Format → Parser → IR → Serializer → Target FormatBenefits
- O(2n) complexity instead of O(n²) - Adding a new format only requires 1 parser + 1 serializer
- Consistent behavior - All conversions go through the same IR
- Extensible - Easy to add new formats without modifying existing code
IR Node Types
The Intermediate Representation supports these node types:
document- Root document nodeelement- XML-like element with name, attributes, childrenobject- Key-value pairsarray- Ordered list of itemstext- Text contentprimitive- String, number, boolean, nullattribute- Element attributecomment- Comment nodecdata- CDATA section
Adding Custom Formats
You can extend the converter with custom formats:
import { engine, FormatParser, FormatSerializer, IRDocument } from '@naman22khater/data-converter';
// Create a parser
const myParser: FormatParser = {
format: 'myformat',
parse(input: string, options?: object): IRDocument {
// Parse input and return IR
return { type: 'document', children: [...] };
}
};
// Create a serializer
const mySerializer: FormatSerializer = {
format: 'myformat',
serialize(ir: IRDocument, options?: object): string {
// Convert IR to string
return '...';
}
};
// Register with engine
engine.registerParser(myParser);
engine.registerSerializer(mySerializer);
// Now you can convert to/from your format
convert(input, { from: 'json', to: 'myformat' });Legacy API
For backward compatibility, direct conversion functions are available:
import { jsonToXml, xmlToJson } from '@naman22khater/data-converter';
const xml = jsonToXml('{"name": "John"}');
const json = xmlToJson('<name>John</name>');Browser Usage
The UMD build can be used directly in browsers:
<script src="https://unpkg.com/@naman22khater/data-converter/dist/index.umd.js"></script>
<script>
const { convert } = DataConverter;
const result = convert('{"hello": "world"}', { from: 'json', to: 'xml' });
console.log(result.output);
</script>Examples
Convert API Response to YAML Config
const apiResponse = `{
"database": {
"host": "localhost",
"port": 5432,
"name": "myapp"
},
"cache": {
"enabled": true,
"ttl": 3600
}
}`;
const yamlConfig = convert(apiResponse, { from: 'json', to: 'yaml' });
console.log(yamlConfig.output);
// database:
// host: localhost
// port: 5432
// name: myapp
// cache:
// enabled: true
// ttl: 3600Parse XML with Attributes
const xml = `
<user id="123" active="true">
<name>John Doe</name>
<email>[email protected]</email>
</user>
`;
const result = convert(xml, { from: 'xml', to: 'json' });
console.log(result.output);
// {
// "user": {
// "@id": "123",
// "@active": "true",
// "name": "John Doe",
// "email": "[email protected]"
// }
// }Author
Naman Khater
License
MIT © Naman Khater
