json-to-csv-ts
v1.0.2
Published
Efficient utility to convert JSON arrays to CSV format in TypeScript.
Maintainers
Readme
json-to-csv-ts
A lightweight, efficient TypeScript utility for converting JSON arrays to CSV format with proper escaping and customizable headers.
Features
- ✅ TypeScript Support: Built with TypeScript and includes type definitions
- ✅ CSV Escaping: Properly handles commas, quotes, and newlines in data
- ✅ Custom Headers: Option to specify custom column headers
- ✅ Zero Dependencies: No external dependencies required
- ✅ ES Modules: Modern ES module support
- ✅ Comprehensive Testing: Full test coverage with Vitest
- ✅ Small Bundle: Lightweight and fast
Installation
npm install json-to-csv-tsUsage
Basic Usage
import { jsonToCsv } from 'json-to-csv-ts';
const data = [
{ name: 'John Doe', age: 30, city: 'New York' },
{ name: 'Jane Smith', age: 25, city: 'Los Angeles' },
{ name: 'Bob Johnson', age: 35, city: 'Chicago' }
];
const csv = jsonToCsv(data);
console.log(csv);Output:
name,age,city
John Doe,30,New York
Jane Smith,25,Los Angeles
Bob Johnson,35,ChicagoCustom Headers
import { jsonToCsv } from 'json-to-csv-ts';
const data = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 }
];
const csv = jsonToCsv(data, {
headers: ['age', 'name']
});
console.log(csv);Output:
age,name
30,John
25,JaneHandling Special Characters
The library automatically escapes special characters in CSV format:
import { jsonToCsv } from 'json-to-csv-ts';
const data = [
{ name: 'John "The Great"', description: 'A person, who likes coding\nand programming' },
{ name: 'Jane', description: 'Simple description' }
];
const csv = jsonToCsv(data);
console.log(csv);Output:
name,description
"John ""The Great""","A person, who likes coding
and programming"
Jane,Simple descriptionAPI Reference
jsonToCsv(data, options?)
Converts an array of JSON objects to CSV format.
Parameters
data(any[]): An array of objects to convert. Each object represents a row.options(JsonToCsvOptions, optional): Configuration options.
Options
interface JsonToCsvOptions {
/**
* An array of strings to use as the CSV headers.
* If not provided, headers will be inferred from the keys of the first object in the data array.
*/
headers?: string[];
}Returns
string: A string in CSV format.
Data Type Support
The library handles various data types:
- Strings: Properly escaped for CSV format
- Numbers: Converted to string representation
- Booleans: Converted to "true" or "false"
- Null/Undefined: Converted to empty strings
- Objects: Converted to "[object Object]"
- Arrays: Converted to comma-separated string (may trigger escaping)
Examples
User Data Export
import { jsonToCsv } from 'json-to-csv-ts';
const users = [
{ id: 1, name: 'John Doe', email: '[email protected]', active: true },
{ id: 2, name: 'Jane Smith', email: '[email protected]', active: false },
{ id: 3, name: 'Bob Johnson', email: '[email protected]', active: true }
];
const csv = jsonToCsv(users);
// Save to file or send as responseProduct Catalog
import { jsonToCsv } from 'json-to-csv-ts';
const products = [
{ name: 'Laptop', price: 999.99, category: 'Electronics', inStock: true },
{ name: 'Book, "Programming Guide"', price: 29.99, category: 'Books', inStock: false }
];
const csv = jsonToCsv(products);Missing Fields Handling
import { jsonToCsv } from 'json-to-csv-ts';
const data = [
{ name: 'John', age: 30 },
{ name: 'Jane' }, // Missing age field
{ name: 'Bob', age: 25, city: 'NYC' } // Extra city field
];
const csv = jsonToCsv(data);
// Headers will be: name,age (from first object)
// Missing fields will be empty stringsError Handling
The function handles edge cases gracefully:
- Empty arrays: Returns empty string
- Non-array input: Returns empty string
- Null/undefined values: Converted to empty strings
- Missing fields: Handled as empty strings
Development
Prerequisites
- Node.js 16+
- npm or yarn
Setup
git clone https://github.com/riyajath-ahamed/json-to-csv.git
cd json-to-csv
npm installScripts
npm run build # Build the project
npm run watch # Build in watch mode
npm test # Run tests in watch mode
npm run test:run # Run tests onceTesting
The project uses Vitest for testing:
npm testContributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Author
riyajath-ahamed
- GitHub: @riyajath-ahamed
- Email: [email protected]
Changelog
1.0.0
- Initial release
- Basic JSON to CSV conversion
- Custom headers support
- Proper CSV escaping
- TypeScript support
- Comprehensive test suite
Support
If you encounter any issues or have questions, please:
- Check the Issues page
- Create a new issue if your problem isn't already reported
- Provide detailed information about your use case and the problem
⭐ Star this repository if you find it helpful!
