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 🙏

© 2024 – Pkg Stats / Ryan Hefner

convert-json-util

v1.0.11

Published

A utility for converting JSON data to various formats

Downloads

68

Readme

Convert JSON Utility

Description

convert-json-util is a versatile utility for converting JSON data into various formats such as CSV, YAML, XML, XLSX, and TXT. This tool is designed to make it easy to transform JSON data into different file types for use in data sharing, reporting, and more. It supports validation using custom schemas, and also allows conversion without any validation if no schema is provided. Additionally, it supports converting JSON data without saving it to a file.

Installation

To install the package, use npm:

npm install convert-json-util

Usage

Importing the Module

To use the convertJson function, import it from the package:

import { convertJson } from 'convert-json-util';

Function Signature

convertJson({
    jsonData: any, 
    schema?: any, 
    saveToFile?: boolean, 
    fileName?: string, 
    fileType?: 'csv' | 'yaml' | 'xml' | 'xlsx' | 'txt' | 'json'
}): { success: boolean, fileData?: string | Buffer, errors?: string[] }

Parameters

  • jsonData: The JSON data to be converted. It can be an object or an array of objects.
  • schema (optional): The schema used to validate the JSON data. This can be any custom schema with parse, safeParse, or validate methods, or it can be omitted entirely for conversion without validation.
  • saveToFile (optional): A boolean indicating whether to save the converted data to a file. Default is false.
  • fileName (optional): The name of the file to save the converted data. Default is "data".
  • fileType (optional): The type of file to convert the data to. Options are 'csv', 'yaml', 'xml', 'xlsx', 'txt', and 'json'. Default is 'txt'.

Return Value

The function returns an object with the following properties:

  • success: A boolean indicating whether the conversion was successful.
  • fileData (optional): The converted data as a string or Buffer. This is only present if success is true.
  • errors (optional): An array of error messages, present if success is false.

Examples

Example 1: Converting JSON to CSV with validation and saving to a file

import { convertJson } from 'convert-json-util';

// Define a custom schema for the JSON data
const customSchema = {
    validate: (data: any) => {
        const errors: string[] = [];
        if (typeof data.name !== 'string') {
            errors.push('Invalid type for name. Expected string.');
        }
        if (typeof data.age !== 'number') {
            errors.push('Invalid type for age. Expected number.');
        }
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (typeof data.email !== 'string' || !emailRegex.test(data.email)) {
            errors.push('Invalid email format.');
        }
        if (errors.length > 0) {
            return { success: false, errors };
        }
        return { success: true, data };
    }
};

const jsonData = [
    { name: "John Doe", age: 30, email: "[email protected]" },
    { name: "Jane Doe", age: 25, email: "[email protected]" }
];

const result = convertJson({ 
    jsonData, 
    schema: customSchema, 
    saveToFile: true, 
    fileName: "users", 
    fileType: "csv" 
});
console.log(result);

Example 2: Converting JSON to YAML without saving to a file or schema

import { convertJson } from 'convert-json-util';

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

const result = convertJson({ 
    jsonData, 
    fileType: "yaml" 
});
console.log(result);

Example 3: Converting JSON to TXT without any validation

import { convertJson } from 'convert-json-util';

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

const result = convertJson({ jsonData, fileType: "txt" });
console.log(result);

Example 4: Printing JSON without any conversion

import { convertJson } from 'convert-json-util';

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

const result = convertJson({ jsonData, fileType: "json" });
console.log(result);

Handling Errors

If an error occurs during conversion, the function will:

  • Print the error message to the console using console.error.
  • Return an object with success: false and an errors array detailing the issues.

Supported File Types

  • CSV: Comma-separated values, useful for spreadsheets and data analysis.
  • YAML: A human-readable data serialization format.
  • XML: Extensible Markup Language, useful for structured data exchange.
  • XLSX: Excel spreadsheet format, useful for advanced data analysis and reporting.
  • TXT: Plain text format, useful for simple data storage and sharing.
  • JSON: Standard JSON format for data exchange and storage.

License

This project is licensed under the MIT License. See the LICENSE file for details.