---
name: "format-json"
description: "将 Markdown 代码块中未格式化的 JSON 格式化为标准的美化 JSON。何时使用：当用户需要美化 .md 文件中的 JSON 数据或要求格式化 JSON 代码块时。"
title: format-json
canonical_url: https://skilld.dev/gh/steelan9199/wechat-publisher/format-json
last_updated: 2026-10-07T07:20:50.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [format-json.js](https://skilld.dev/api/skills-raw/steelan9199/wechat-publisher/format-json/format-json.js).
>
> If the user asked to install this Skill, run `npx skilld install steelan9199/wechat-publisher/format-json`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/format-json`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/steelan9199/wechat-publisher/format-json) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/format-json`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/format-json --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/format-json --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Format JSON in Markdown

## 功能概述

本 Skill 用于扫描 Markdown 文件中的代码块，自动将其中未格式化（压缩成一行）的 JSON 数据转换为标准缩进格式（2 空格），使其易于人类阅读。支持 ` ``` `、` ```json ` 等任意语言标识的代码块；只要代码块内容能被 `JSON.parse()` 成功解析，就会自动美化，解析失败则保持原样不变。

## 环境说明

- 本 Skill 的脚本 `format-json.js` 与 `SKILL.md` 位于同一目录。
- 下文以 `<skill-dir>` 指代该目录（即 skill 的安装目录）。

## 执行步骤

| 步骤 | 动作           | 命令/操作                                         |
| ---- | -------------- | ------------------------------------------------- |
| 1    | 获取目标文件   | 确定用户指定的 `.md` 文件路径；如未指定，询问用户 |
| 2    | 运行格式化脚本 | 执行 `node <skill-dir>/format-json.js <文件路径>` |
| 3    | 确认执行结果   | 检查控制台是否输出 "JSON 格式化完成"              |
| 4    | 向用户反馈     | 报告格式化完成，并展示变更后的 JSON 代码块        |

## 决策逻辑

| 条件                      | 执行动作                            |
| ------------------------- | ----------------------------------- |
| 用户指定了 `.md` 文件路径 | 直接运行脚本                        |
| 用户未指定文件路径        | 询问用户需要格式化的 `.md` 文件路径 |
| 脚本执行失败              | 按【脚本说明】手动执行格式化步骤    |

## 脚本说明

本 skill 目录下附带脚本 [format-json.js](https://skilld.dev/api/skills-raw/steelan9199/wechat-publisher/format-json/format-json/format-json.js)，逻辑如下：

1. 读取目标 `.md` 文件内容。
2. 正则匹配所有代码块：`(```(?:\w+)?\n)([\s\S]*?)(\n```)`。
3. 对每个代码块内容执行 `trim()`，去除前后空白字符（包括空行）。
4. 尝试 `JSON.parse()` 解析。
   - 成功：替换为 `JSON.stringify(parsed, null, 2)`。
   - 失败：保留原样。
5. 将结果写回原文件。

## 错误处理

| 错误场景              | 处理方式                                               |
| --------------------- | ------------------------------------------------------ |
| 文件不存在            | 检查路径是否正确，提示用户提供正确的 `.md` 文件路径    |
| 脚本执行失败          | 检查 Node.js 环境；如环境问题则按【脚本说明】手动执行  |
| 未找到可格式化的 JSON | 向用户说明文件中不存在可被 `JSON.parse()` 解析的代码块 |

## 示例

### Before

````markdown
```json
{ "users": [{ "name": "Alice", "age": 30 }], "count": 1 }
```
````

### After

````markdown
```json
{
  "users": [
    {
      "name": "Alice",
      "age": 30
    }
  ],
  "count": 1
}
```
````
