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

format-validator-anian

v1.0.1

Published

轻量级、无框架依赖的多格式校验与格式化工具库,支持 **JSON、XML、JavaScript、YAML、Properties** 五种常见格式,可通过 `script` 标签直接引入或模块化导入,兼容浏览器与 Node.js 环境。

Readme

FormatValidator

轻量级、无框架依赖的多格式校验与格式化工具库,支持 JSON、XML、JavaScript、YAML、Properties 五种常见格式,可通过 script 标签直接引入或模块化导入,兼容浏览器与 Node.js 环境。

目录

快速开始

1. 环境准备

无需额外依赖(打包时已集成成熟工具库),支持两种引入方式:

方式 1:Script 标签引入(浏览器环境)

\<!-- 引入打包后的 IIFE 格式文件 -->

\<script src="dist/format-validator.iife.js">\</script>

\<!-- 直接通过 window.FormatValidator 调用 API -->

方式 2:模块化导入(Node.js/ 现代前端工程)

// ES Module 导入

import FormatValidator from './src/index.js';

// 或按需导入

import { validJson, formatYaml } from './src/index.js';

// CommonJS 导入(需配合 Vite/Rollup 打包)

const FormatValidator = require('./dist/format-validator.cjs');

2. 依赖说明

核心功能基于行业成熟工具实现,确保稳定性与准确性:

| 功能领域 | 依赖库 | 版本要求 | | ------------- | ----------------- | ------- | | JSON 解析 / 格式化 | json5 | ^2.2.3 | | XML 解析 / 序列化 | xmldom | ^0.6.0 | | JS 语法解析 | acorn | ^8.10.0 | | JS 代码生成 | escodegen | ^2.1.0 | | YAML 解析 / 格式化 | js-yaml | ^4.1.0 | | Properties 处理 | properties-parser | ^0.6.0 |

核心能力

  • 多格式支持:覆盖 JSON、XML、JS、YAML、Properties 主流配置 / 代码格式

  • 双模式验证:JSON 支持「宽松模式」(兼容 JSON5)与「严格模式」(标准 JSON)

  • 安全无风险:JS 验证基于语法解析(不执行代码),避免注入风险

  • 统一返回格式:所有方法返回结构一致的结果对象,便于错误处理

API 文档

所有方法返回统一结构的结果对象,分为「验证结果」与「格式化结果」两类:

通用结果结构

验证结果对象

| 属性名 | 类型 | 说明 | | -------------------------- | ------- | ---------------------------- | | valid | boolean | true = 格式合法,false = 格式非法 | | error | string | 仅失败时存在,描述错误原因 | | position/line/column | number | 可选,错误位置信息(格式不同返回不同) |

格式化结果对象

| 属性名 | 类型 | 说明 | | --------------- | ------- | --------------------------- | | success | boolean | true = 格式化成功,false = 失败 | | result | string | 仅成功时存在,返回格式化后的内容 | | error | string | 仅失败时存在,描述错误原因 | | line/column | number | 可选,错误位置信息 |

1. JSON 相关方法

1.1 validJson(str, strict = false)

功能:验证字符串是否为合法 JSON(支持宽松 / 严格双模式)

| 参数 | 类型 | 默认值 | 说明 | | -------- | ------- | ----- | ---------------------------------------------------------------------- | | str | string | - | 待验证的字符串(非字符串直接返回失败) | | strict | boolean | false | 严格模式开关:- false:允许 JSON5 语法(键名无引号、注释等)- true:仅允许标准 JSON 语法(键名必须双引号) |

示例

// 宽松模式(通过)

FormatValidator.validJson('{"name": "测试", age: 30}');&#x20;

// { valid: true }

// 严格模式(失败,键名无引号)

FormatValidator.validJson('{"name": "测试", age: 30}', true);&#x20;

// { valid: false, error: "Unexpected token a in JSON at position 18", position: 18 }

1.2 formatJson(str, space = 2, strict = true)

功能:格式化 JSON 字符串,支持标准 / 宽松输出

| 参数 | 类型 | 默认值 | 说明 | | -------- | ------- | ---- | ------------------------------------------------------------ | | str | string | - | 待格式化的字符串(支持 JSON5 宽松格式) | | space | number | 2 | 缩进空格数(0 = 压缩为单行) | | strict | boolean | true | 输出模式:- true:输出标准 JSON(双引号、无注释)- false:输出 JSON5 格式(无引号键名) |

示例

FormatValidator.formatJson('{name: "测试", age: 30}', 2, true);

// {&#x20;

//   success: true,&#x20;

//   result: "{\n  \\"name\\": \\"测试\\",\n  \\"age\\": 30\n}"&#x20;

// }

2. XML 相关方法

2.1 validXml(str)

功能:验证 XML 格式合法性(检测标签闭合、语法错误)

| 参数 | 类型 | 说明 | | ----- | ------ | ------------ | | str | string | 待验证的 XML 字符串 |

示例

// 合法 XML(通过)

FormatValidator.validXml('\<root>\<user>\<age>30\</age>\</user>\</root>');

// { valid: true }

// 非法 XML(标签未闭合,失败)

FormatValidator.validXml('\<root>\<user>\</root>');

// { valid: false, error: "Opening and ending tag mismatch: user line 1 and root" }

2.2 formatXml(str, indent = 2)

功能:格式化 XML 字符串,自动处理缩进与换行

| 参数 | 类型 | 默认值 | 说明 | | -------- | ------ | --- | ---------------- | | str | string | - | 待格式化的 XML 字符串 | | indent | number | 2 | 缩进空格数(0 = 压缩为单行) |

示例

const unformatted = '\<root>\<user>\<name>test\</name>\</user>\</root>';

FormatValidator.formatXml(unformatted, 2);

// {&#x20;

//   success: true,&#x20;

//   result: "\<root>\n  \<user>\n    \<name>test\</name>\n  \</user>\n\</root>"&#x20;

// }

3. JavaScript 相关方法

3.1 validJs(str)

功能:验证 JS 代码语法合法性(基于 Acorn 解析,不执行代码)

| 参数 | 类型 | 说明 | | ----- | ------ | ------------- | | str | string | 待验证的 JS 代码字符串 |

示例

// 合法 JS(通过)

FormatValidator.validJs('const add = (a, b) => a + b;');

// { valid: true }

// 非法 JS(缺少分号,失败)

FormatValidator.validJs('const add = (a, b) => a + b function test() {}');

// { valid: false, error: "Unexpected token 'function'", line: 1, column: 28 }

3.2 formatJs(str, options = {})

功能:格式化 JS 代码,支持自定义缩进、引号风格

| 参数 | 类型 | 默认值 | 说明 | | --------- | ------ | --- | ----------------------------------------------------------------------------------------------------------------------------- | | str | string | - | 待格式化的 JS 代码字符串 | | options | object | {} | 格式化配置(继承 escodegen 选项):- indent.style:缩进字符(默认 " ")- quotes:引号风格("single"/"double")- compact:是否压缩(true/false) |

示例

FormatValidator.formatJs('function add(a,b){return a+b;}', { quotes: 'double' });

// {&#x20;

//   success: true,&#x20;

//   result: "function add(a, b) {\n  return a + b;\n}"&#x20;

// }

4. YAML 相关方法

4.1 validYaml(str)

功能:验证 YAML 格式合法性(支持 YAML 1.2 规范)

| 参数 | 类型 | 说明 | | ----- | ------ | ------------- | | str | string | 待验证的 YAML 字符串 |

示例

// 合法 YAML(通过)

const validYaml = \`

name: 测试

age: 30

hobbies:

&#x20; \- 阅读

&#x20; \- 运动

\`;

FormatValidator.validYaml(validYaml);

// { valid: true }

// 非法 YAML(缩进错误,失败)

const invalidYaml = \`

name: 测试

hobbies:

\- 阅读

&#x20; \- 运动

\`;

FormatValidator.validYaml(invalidYaml);

// { valid: false, error: "bad indentation of a sequence entry", line: 4, column: 3 }

4.2 formatYaml(str, indent = 2)

功能:格式化 YAML 字符串,规范缩进与键值对格式

| 参数 | 类型 | 默认值 | 说明 | | -------- | ------ | --- | ------------------ | | str | string | - | 待格式化的 YAML 字符串 | | indent | number | 2 | 缩进空格数(YAML 推荐 2/4) |

示例

const unformatted = 'name:测试\nage:30\nhobbies:\[-阅读,-运动]';

FormatValidator.formatYaml(unformatted, 2);

// {&#x20;

//   success: true,&#x20;

//   result: "name: 测试\nage: 30\nhobbies:\n  - 阅读\n  - 运动\n"&#x20;

// }

5. Properties 相关方法

5.1 validProperties(str)

功能:验证 Properties 格式合法性(Java 配置文件格式)

| 参数 | 类型 | 说明 | | ----- | ------ | ------------------- | | str | string | 待验证的 Properties 字符串 |

示例

// 合法 Properties(通过)

const validProps = \`

\# 应用配置

app.name=测试应用

app.version=1.0.0

\`;

FormatValidator.validProperties(validProps);

// { valid: true }

// 非法 Properties(多等号,失败)

FormatValidator.validProperties('app.enabled=true=1');

// { valid: false, error: "Invalid line: app.enabled=true=1", line: 1 }

错误处理

所有方法均返回结构化错误信息,便于定位问题:

// 示例:YAML 验证错误处理

const result = FormatValidator.validYaml('name: 测试\nage: 30.5.6');

if (!result.valid) {

&#x20; console.error(\`验证失败:\${result.error}\`);

&#x20; console.error(\`错误位置:第 \${result.line} 行,第 \${result.column} 列\`);

}

常见错误类型

  1. 参数类型错误:输入非字符串时,返回 Input must be a string

  2. 语法错误:如 JSON 键名无引号、XML 标签未闭合等,返回具体语法问题

  3. 缩进错误:YAML/Properties 格式对缩进敏感,错误时返回行号与列号

浏览器兼容性

| 浏览器 | 支持版本 | 说明 | | ------- | ----- | ------------------- | | Chrome | 58+ | 完全支持 | | Firefox | 54+ | 完全支持 | | Safari | 11.1+ | 完全支持 | | Edge | 79+ | 基于 Chromium 内核,完全支持 | | IE | 不支持 | 不兼容 ES6+ 语法 |

常见问题(FAQ)

Q1:为什么 validJson 允许键名无引号?

A1:默认启用「宽松模式」(基于 JSON5),若需严格验证标准 JSON,需将 strict 参数设为 true

Q2:Node.js 环境中 validXml 报错怎么办?

A2:Node.js 无原生 DOMParser,需额外安装 xmldom 依赖(npm install xmldom --save),打包时会自动集成。

Q3:formatJs 能否压缩代码?

A3:可以,通过 options.compact: true 实现:

FormatValidator.formatJs('function add(a, b) { return a + b; }', { compact: true });

// 返回压缩后:"function add(a,b){return a+b;}"

Q4:Properties 格式化后注释会丢失吗?

A4:不会,格式化会保留原始注释,并在文件顶部添加 # Formatted by FormatValidator 标识。