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

json5converter

v1.0.0

Published

JSON5 to JSON converter

Readme

JSON5 Converter - Documentation

Документация на русском

Overview

json5converter is a package for converting JSON5 to standard JSON. It provides both synchronous and asynchronous methods for working with strings and files.

Installation

npm install json5converter

API

Class Json5Converter

The main class that provides static methods for conversion.

Methods

Json5Converter.convertText(json5String: string): string

Converts a JSON5 string to a formatted JSON string.

Parameters:

  • json5String (string): A string in JSON5 format

Returns:

  • string: Formatted JSON string

Example:

import converter from 'json5converter';

const json5String = `{
    // comment
    name: 'John',
    age: 30,
    hobbies: ['reading', 'gaming']
}`;

const jsonString = converter.convertText(json5String);
console.log(jsonString);

Json5Converter.convertFile(inputPath: string, outputPath: string): Promise<void>

Asynchronously converts a JSON5 file to a JSON file.

Parameters:

  • inputPath (string): Path to the source JSON5 file
  • outputPath (string): Path to save the JSON file

Example:

import { Json5Converter } from 'json5converter';

await Json5Converter.convertFile('./config.json5', './config.json');

Json5Converter.convertFileSync(inputPath: string, outputPath: string): void

Synchronous version of file conversion.

Parameters:

  • inputPath (string): Path to the source JSON5 file
  • outputPath (string): Path to save the JSON file

Example:

import { Json5Converter } from 'json5converter';

Json5Converter.convertFileSync('./config.json5', './config.json');

Helper Functions

The package also provides wrapper functions for convenience:

convertText(json5String: string): string

import { convertText } from 'json5converter';
const json = convertText(json5String);

convertFile(inputPath: string, outputPath: string): Promise<void>

import { convertFile } from 'json5converter';
await convertFile('./input.json5', './output.json');

convertFileSync(inputPath: string, outputPath: string): void

import { convertFileSync } from 'json5converter';
convertFileSync('./input.json5', './output.json');

Usage Examples

Example 1: Converting a String

import { convertText } from 'json5converter';

const json5 = `
{
    // Application settings
    appName: "My App",
    version: "1.0.0",
    debug: true,
    api: {
        endpoint: "https://api.example.com",
        timeout: 5000
    }
}
`;

const json = convertText(json5);
console.log(json);

Example 2: Converting Files

import { convertFile } from 'json5converter';

// Asynchronous conversion
async function convertConfig() {
    try {
        await convertFile('./app-config.json5', './app-config.json');
        console.log('Conversion completed');
    } catch (error) {
        console.error('Conversion error:', error);
    }
}

convertConfig();

Example 3: Using CommonJS (if set up)

const { convertFileSync } = require('json5converter');

// Synchronous conversion
convertFileSync('./settings.json5', './settings.json');

Features

Supported JSON5 Features:

  • Comments (single-line and multi-line)
  • Object keys without quotes
  • Strings with single quotes
  • Trailing commas in objects and arrays
  • Multi-line strings
  • Numbers in various formats (hexadecimal, floating-point, etc.)

Error Handling:

All methods throw exceptions in case of parsing errors or file operation errors.

TypeScript Support

The package includes TypeScript type declarations, providing autocompletion and type checking.

License

MIT License

Links

Support

To report bugs and suggest features, please use the GitHub Issues system.


JSON5 Converter - Документация

Documentation in English

Обзор

json5converter — это пакет для конвертации JSON5 в стандартный JSON. Он предоставляет как синхронные, так и асинхронные методы для работы со строками и файлами.

Установка

npm install json5converter

API

Класс Json5Converter

Основной класс, предоставляющий статические методы для конвертации.

Методы

Json5Converter.convertText(json5String: string): string

Конвертирует строку JSON5 в отформатированную строку JSON.

Параметры:

  • json5String (string): Строка в формате JSON5

Возвращает:

  • string: Отформатированная строка JSON

Пример:

import converter from 'json5converter';

const json5String = `{
    // комментарий
    name: 'John',
    age: 30,
    hobbies: ['reading', 'gaming']
}`;

const jsonString = converter.convertText(json5String);
console.log(jsonString);

Json5Converter.convertFile(inputPath: string, outputPath: string): Promise<void>

Асинхронно конвертирует файл JSON5 в файл JSON.

Параметры:

  • inputPath (string): Путь к исходному файлу JSON5
  • outputPath (string): Путь для сохранения JSON файла

Пример:

import { Json5Converter } from 'json5converter';

await Json5Converter.convertFile('./config.json5', './config.json');

Json5Converter.convertFileSync(inputPath: string, outputPath: string): void

Синхронная версия конвертации файла.

Параметры:

  • inputPath (string): Путь к исходному файлу JSON5
  • outputPath (string): Путь для сохранения JSON файла

Пример:

import { Json5Converter } from 'json5converter';

Json5Converter.convertFileSync('./config.json5', './config.json');

Функции-хелперы

Пакет также предоставляет функции-обёртки для удобства использования:

convertText(json5String: string): string

import { convertText } from 'json5converter';
const json = convertText(json5String);

convertFile(inputPath: string, outputPath: string): Promise<void>

import { convertFile } from 'json5converter';
await convertFile('./input.json5', './output.json');

convertFileSync(inputPath: string, outputPath: string): void

import { convertFileSync } from 'json5converter';
convertFileSync('./input.json5', './output.json');

Примеры использования

Пример 1: Конвертация строки

import { convertText } from 'json5converter';

const json5 = `
{
    // Настройки приложения
    appName: "My App",
    version: "1.0.0",
    debug: true,
    api: {
        endpoint: "https://api.example.com",
        timeout: 5000
    }
}
`;

const json = convertText(json5);
console.log(json);

Пример 2: Конвертация файлов

import { convertFile } from 'json5converter';

// Асинхронная конвертация
async function convertConfig() {
    try {
        await convertFile('./app-config.json5', './app-config.json');
        console.log('Конвертация завершена');
    } catch (error) {
        console.error('Ошибка конвертации:', error);
    }
}

convertConfig();

Пример 3: Использование в CommonJS (если настроено)

const { convertFileSync } = require('json5converter');

// Синхронная конвертация
convertFileSync('./settings.json5', './settings.json');

Особенности

Поддерживаемые функции JSON5:

  • Комментарии (однострочные и многострочные)
  • Ключи объектов без кавычек
  • Строки с одинарными кавычками
  • Завершающие запятые в объектах и массивах
  • Многострочные строки
  • Числа в различных форматах (шестнадцатеричные, с плавающей точкой и т.д.)

Обработка ошибок:

Все методы бросают исключения при возникновении ошибок парсинга или операций с файлами.

TypeScript поддержка

Пакет включает TypeScript декларации типов, что обеспечивает автодополнение и проверку типов.

Лицензия

MIT License

Ссылки

Поддержка

Для сообщения об ошибках и предложений функций используйте систему Issues GitHub.