scripts/Json-Tidy.ps1
17.8 KB| 1 | #requires -Version 7.0 |
| 2 | <# |
| 3 | Json-Tidy.ps1 —— JSON 格式化 / 压缩 / 校验 / 键排序 / JSONL 互转 |
| 4 | |
| 5 | 纯本地运行,不联网,不写临时文件。默认把结果打印到屏幕, |
| 6 | 只有显式传 -InPlace 或 -OutFile 时才写文件。 |
| 7 | 数字与字符串字面量按原文原样保留(不会把 1.0 变成 1、把 1e5 变成 100000、 |
| 8 | 不会把 \u00e9 改成 é);写回时保持原有的 UTF-8 BOM 与换行符风格。 |
| 9 | |
| 10 | 用法示例: |
| 11 | pwsh Json-Tidy.ps1 -Path data.json -Action format |
| 12 | pwsh Json-Tidy.ps1 -Path data.json -Action compact -InPlace |
| 13 | pwsh Json-Tidy.ps1 -Path data.json -Action validate |
| 14 | pwsh Json-Tidy.ps1 -Path data.json -Action sort -Indent 4 -OutFile sorted.json |
| 15 | pwsh Json-Tidy.ps1 -Path list.json -Action to-lines -OutFile list.jsonl |
| 16 | pwsh Json-Tidy.ps1 -Path list.jsonl -Action from-lines |
| 17 | |
| 18 | 退出码:0 成功;2 JSON 语法错误;3 文件、参数或写出问题。 |
| 19 | #> |
| 20 | [CmdletBinding()] |
| 21 | param( |
| 22 | [Parameter(Mandatory = $true, Position = 0)] |
| 23 | [string]$Path, |
| 24 | |
| 25 | [ValidateSet('format', 'compact', 'validate', 'sort', 'to-lines', 'from-lines')] |
| 26 | [string]$Action = 'format', |
| 27 | |
| 28 | [ValidateRange(0, 8)] |
| 29 | [int]$Indent = 2, |
| 30 | |
| 31 | [switch]$InPlace, |
| 32 | |
| 33 | [string]$OutFile |
| 34 | ) |
| 35 | |
| 36 | $ErrorActionPreference = 'Stop' |
| 37 | Set-StrictMode -Version Latest |
| 38 | |
| 39 | # ---------------- 编译型核心(内存编译,不落地文件) ---------------- |
| 40 | if (-not ('JsonTidy.Core' -as [type])) { |
| 41 | Add-Type -TypeDefinition @' |
| 42 | using System; |
| 43 | using System.Collections.Generic; |
| 44 | using System.Text; |
| 45 | using System.Text.RegularExpressions; |
| 46 | |
| 47 | namespace JsonTidy |
| 48 | { |
| 49 | public class ParseError : Exception |
| 50 | { |
| 51 | public int Pos; |
| 52 | public ParseError(string message, int pos) : base(message) { Pos = pos; } |
| 53 | } |
| 54 | |
| 55 | internal class Node |
| 56 | { |
| 57 | public int Kind; // 1 对象, 2 数组, 3 字面量 |
| 58 | public List<Member> Members; |
| 59 | public List<Node> Items; |
| 60 | public string Raw; |
| 61 | } |
| 62 | |
| 63 | internal class Member |
| 64 | { |
| 65 | public string Key; // 含引号的原始键文本 |
| 66 | public Node Value; |
| 67 | } |
| 68 | |
| 69 | public static class Core |
| 70 | { |
| 71 | private static string s; |
| 72 | private static int p; |
| 73 | private static int n; |
| 74 | private static readonly Regex NumRe = |
| 75 | new Regex("-?(0|[1-9][0-9]*)(\\.[0-9]+)?([eE][+-]?[0-9]+)?", RegexOptions.Compiled); |
| 76 | |
| 77 | private static void Fail(string message) |
| 78 | { |
| 79 | throw new ParseError(message, p); |
| 80 | } |
| 81 | |
| 82 | private static void SkipWs() |
| 83 | { |
| 84 | while (p < n) |
| 85 | { |
| 86 | char c = s[p]; |
| 87 | if (c == ' ' || c == '\t' || c == '\n' || c == '\r') p++; |
| 88 | else break; |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | private static Node ParseString() |
| 93 | { |
| 94 | int start = p; |
| 95 | p++; // 跳过左引号 |
| 96 | while (true) |
| 97 | { |
| 98 | if (p >= n) Fail("字符串没有结束(缺少右引号)"); |
| 99 | char c = s[p]; |
| 100 | if (c == '"') { p++; break; } |
| 101 | if (c == '\\') |
| 102 | { |
| 103 | if (p + 1 >= n) Fail("字符串以反斜杠结尾"); |
| 104 | char e = s[p + 1]; |
| 105 | if (e == 'u') |
| 106 | { |
| 107 | if (p + 5 >= n) Fail("转义序列 \\u 后需要 4 位十六进制数字"); |
| 108 | string hex = s.Substring(p + 2, 4); |
| 109 | for (int i = 0; i < 4; i++) |
| 110 | { |
| 111 | char h = hex[i]; |
| 112 | bool ok = (h >= '0' && h <= '9') || (h >= 'a' && h <= 'f') || (h >= 'A' && h <= 'F'); |
| 113 | if (!ok) Fail("转义序列 \\u" + hex + " 不是 4 位十六进制数字"); |
| 114 | } |
| 115 | p += 6; |
| 116 | continue; |
| 117 | } |
| 118 | if ("\"\\/bfnrt".IndexOf(e) < 0) Fail("不支持的转义字符:\\" + e); |
| 119 | p += 2; |
| 120 | continue; |
| 121 | } |
| 122 | if ((int)c < 0x20) Fail("字符串里有未转义的控制字符(换行、制表符等必须先转义)"); |
| 123 | p++; |
| 124 | } |
| 125 | Node node = new Node(); |
| 126 | node.Kind = 3; |
| 127 | node.Raw = s.Substring(start, p - start); |
| 128 | return node; |
| 129 | } |
| 130 | |
| 131 | private static Node ParseNumber() |
| 132 | { |
| 133 | Match m = NumRe.Match(s, p); |
| 134 | if (!m.Success || m.Index != p) Fail("不认识的值:" + (p < n ? s[p].ToString() : "(结尾)")); |
| 135 | p += m.Length; |
| 136 | Node node = new Node(); |
| 137 | node.Kind = 3; |
| 138 | node.Raw = m.Value; |
| 139 | return node; |
| 140 | } |
| 141 | |
| 142 | private static Node ParseLiteral() |
| 143 | { |
| 144 | if (p + 4 <= n && string.CompareOrdinal(s, p, "true", 0, 4) == 0) return Raw("true", 4); |
| 145 | if (p + 5 <= n && string.CompareOrdinal(s, p, "false", 0, 5) == 0) return Raw("false", 5); |
| 146 | if (p + 4 <= n && string.CompareOrdinal(s, p, "null", 0, 4) == 0) return Raw("null", 4); |
| 147 | Fail("不认识的值:" + s[p]); |
| 148 | return null; |
| 149 | } |
| 150 | |
| 151 | private static Node Raw(string text, int length) |
| 152 | { |
| 153 | p += length; |
| 154 | Node node = new Node(); |
| 155 | node.Kind = 3; |
| 156 | node.Raw = text; |
| 157 | return node; |
| 158 | } |
| 159 | |
| 160 | private static Node ParseValue() |
| 161 | { |
| 162 | SkipWs(); |
| 163 | if (p >= n) Fail("内容意外结束,缺少值"); |
| 164 | char c = s[p]; |
| 165 | if (c == '{') return ParseObject(); |
| 166 | if (c == '[') return ParseArray(); |
| 167 | if (c == '"') return ParseString(); |
| 168 | if (c == 't' || c == 'f' || c == 'n') return ParseLiteral(); |
| 169 | return ParseNumber(); |
| 170 | } |
| 171 | |
| 172 | private static Node ParseObject() |
| 173 | { |
| 174 | p++; // { |
| 175 | SkipWs(); |
| 176 | Node node = new Node(); |
| 177 | node.Kind = 1; |
| 178 | node.Members = new List<Member>(); |
| 179 | if (p < n && s[p] == '}') { p++; return node; } |
| 180 | while (true) |
| 181 | { |
| 182 | SkipWs(); |
| 183 | if (p >= n) Fail("对象没有结束(缺少右花括号)"); |
| 184 | if (s[p] != '"') Fail("对象的键必须是双引号字符串"); |
| 185 | Node keyNode = ParseString(); |
| 186 | SkipWs(); |
| 187 | if (p >= n || s[p] != ':') Fail("键 " + keyNode.Raw + " 后面缺少冒号"); |
| 188 | p++; |
| 189 | Member mem = new Member(); |
| 190 | mem.Key = keyNode.Raw; |
| 191 | mem.Value = ParseValue(); |
| 192 | node.Members.Add(mem); |
| 193 | SkipWs(); |
| 194 | if (p >= n) Fail("对象没有结束(缺少右花括号)"); |
| 195 | if (s[p] == ',') |
| 196 | { |
| 197 | p++; |
| 198 | SkipWs(); |
| 199 | if (p < n && s[p] == '}') Fail("对象末尾多了一个逗号"); |
| 200 | continue; |
| 201 | } |
| 202 | if (s[p] == '}') { p++; return node; } |
| 203 | Fail("对象的成员之间缺少逗号(遇到 '" + s[p] + "')"); |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | private static Node ParseArray() |
| 208 | { |
| 209 | p++; // [ |
| 210 | SkipWs(); |
| 211 | Node node = new Node(); |
| 212 | node.Kind = 2; |
| 213 | node.Items = new List<Node>(); |
| 214 | if (p < n && s[p] == ']') { p++; return node; } |
| 215 | while (true) |
| 216 | { |
| 217 | node.Items.Add(ParseValue()); |
| 218 | SkipWs(); |
| 219 | if (p >= n) Fail("数组没有结束(缺少右方括号)"); |
| 220 | if (s[p] == ',') |
| 221 | { |
| 222 | p++; |
| 223 | SkipWs(); |
| 224 | if (p < n && s[p] == ']') Fail("数组末尾多了一个逗号"); |
| 225 | continue; |
| 226 | } |
| 227 | if (s[p] == ']') { p++; return node; } |
| 228 | Fail("数组元素之间缺少逗号(遇到 '" + s[p] + "')"); |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | private static Node ParseDocument(string text) |
| 233 | { |
| 234 | s = text; |
| 235 | p = 0; |
| 236 | n = text.Length; |
| 237 | SkipWs(); |
| 238 | if (p >= n) Fail("内容意外结束,缺少值"); |
| 239 | Node root = ParseValue(); |
| 240 | SkipWs(); |
| 241 | if (p < n) Fail("结束处还有多余内容"); |
| 242 | return root; |
| 243 | } |
| 244 | |
| 245 | // ---------- 输出 ---------- |
| 246 | private static void Compact(Node node, StringBuilder sb) |
| 247 | { |
| 248 | if (node.Kind == 3) { sb.Append(node.Raw); return; } |
| 249 | if (node.Kind == 2) |
| 250 | { |
| 251 | sb.Append('['); |
| 252 | for (int i = 0; i < node.Items.Count; i++) |
| 253 | { |
| 254 | if (i > 0) sb.Append(','); |
| 255 | Compact(node.Items[i], sb); |
| 256 | } |
| 257 | sb.Append(']'); |
| 258 | return; |
| 259 | } |
| 260 | sb.Append('{'); |
| 261 | for (int i = 0; i < node.Members.Count; i++) |
| 262 | { |
| 263 | if (i > 0) sb.Append(','); |
| 264 | sb.Append(node.Members[i].Key).Append(':'); |
| 265 | Compact(node.Members[i].Value, sb); |
| 266 | } |
| 267 | sb.Append('}'); |
| 268 | } |
| 269 | |
| 270 | private static bool IsScalar(Node node) { return node.Kind == 3; } |
| 271 | |
| 272 | private static void Pretty(Node node, StringBuilder sb, int level, int indent, bool sortKeys, string nl) |
| 273 | { |
| 274 | string pad = new string(' ', level * indent); |
| 275 | string inner = new string(' ', (level + 1) * indent); |
| 276 | if (node.Kind == 3) { sb.Append(node.Raw); return; } |
| 277 | if (node.Kind == 2) |
| 278 | { |
| 279 | if (node.Items.Count == 0) { sb.Append("[]"); return; } |
| 280 | bool allScalar = true; |
| 281 | foreach (Node it in node.Items) { if (!IsScalar(it)) { allScalar = false; break; } } |
| 282 | if (allScalar) |
| 283 | { |
| 284 | StringBuilder tmp = new StringBuilder(); |
| 285 | Compact(node, tmp); |
| 286 | if (tmp.Length <= 72) |
| 287 | { |
| 288 | sb.Append('['); |
| 289 | for (int i = 0; i < node.Items.Count; i++) |
| 290 | { |
| 291 | if (i > 0) sb.Append(", "); |
| 292 | sb.Append(node.Items[i].Raw); |
| 293 | } |
| 294 | sb.Append(']'); |
| 295 | return; |
| 296 | } |
| 297 | } |
| 298 | sb.Append('[').Append(nl); |
| 299 | for (int i = 0; i < node.Items.Count; i++) |
| 300 | { |
| 301 | if (i > 0) sb.Append(',').Append(nl); |
| 302 | sb.Append(inner); |
| 303 | Pretty(node.Items[i], sb, level + 1, indent, sortKeys, nl); |
| 304 | } |
| 305 | sb.Append(nl).Append(pad).Append(']'); |
| 306 | return; |
| 307 | } |
| 308 | if (node.Members.Count == 0) { sb.Append("{}"); return; } |
| 309 | List<Member> members = node.Members; |
| 310 | if (sortKeys) |
| 311 | { |
| 312 | members = new List<Member>(node.Members); |
| 313 | members.Sort(delegate (Member a, Member b) |
| 314 | { |
| 315 | int c = string.Compare(a.Key, b.Key, StringComparison.OrdinalIgnoreCase); |
| 316 | if (c != 0) return c; |
| 317 | return string.CompareOrdinal(a.Key, b.Key); |
| 318 | }); |
| 319 | } |
| 320 | sb.Append('{').Append(nl); |
| 321 | for (int i = 0; i < members.Count; i++) |
| 322 | { |
| 323 | if (i > 0) sb.Append(',').Append(nl); |
| 324 | sb.Append(inner).Append(members[i].Key).Append(": "); |
| 325 | Pretty(members[i].Value, sb, level + 1, indent, sortKeys, nl); |
| 326 | } |
| 327 | sb.Append(nl).Append(pad).Append('}'); |
| 328 | } |
| 329 | |
| 330 | private static string KindName(Node node) |
| 331 | { |
| 332 | if (node.Kind == 1) return "对象"; |
| 333 | if (node.Kind == 2) return "数组"; |
| 334 | if (node.Kind == 3) |
| 335 | { |
| 336 | if (node.Raw.Length > 0 && node.Raw[0] == '"') return "字符串"; |
| 337 | if (node.Raw == "true" || node.Raw == "false") return "布尔值"; |
| 338 | if (node.Raw == "null") return "null"; |
| 339 | return "数字"; |
| 340 | } |
| 341 | return "值"; |
| 342 | } |
| 343 | |
| 344 | private static string StripQuotes(string raw) |
| 345 | { |
| 346 | if (raw.Length >= 2 && raw[0] == '"' && raw[raw.Length - 1] == '"') return raw.Substring(1, raw.Length - 2); |
| 347 | return raw; |
| 348 | } |
| 349 | |
| 350 | public static string Run(string text, string action, int indent, string nl) |
| 351 | { |
| 352 | if (action == "from-lines") |
| 353 | { |
| 354 | List<Node> rows = new List<Node>(); |
| 355 | string[] lines = text.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'); |
| 356 | for (int i = 0; i < lines.Length; i++) |
| 357 | { |
| 358 | if (lines[i].Trim().Length == 0) continue; |
| 359 | try { rows.Add(ParseDocument(lines[i])); } |
| 360 | catch (ParseError ex) |
| 361 | { |
| 362 | int col2 = 1; |
| 363 | int limit = Math.Min(ex.Pos, lines[i].Length); |
| 364 | for (int k = 0; k < limit; k++) { col2++; } |
| 365 | throw new ParseError("第 " + (i + 1) + " 行第 " + col2 + " 列:" + ex.Message, -1); |
| 366 | } |
| 367 | } |
| 368 | if (rows.Count == 0) throw new ParseError("输入里没有任何一行 JSON", 0); |
| 369 | Node root = new Node(); |
| 370 | root.Kind = 2; |
| 371 | root.Items = rows; |
| 372 | StringBuilder arr = new StringBuilder(); |
| 373 | Pretty(root, arr, 0, indent, false, nl); |
| 374 | return arr.ToString() + nl; |
| 375 | } |
| 376 | |
| 377 | Node doc = ParseDocument(text); |
| 378 | StringBuilder sb = new StringBuilder(); |
| 379 | if (action == "validate") return "OK:合法 JSON,顶层是" + KindName(doc) + nl; |
| 380 | if (action == "format") { Pretty(doc, sb, 0, indent, false, nl); return sb.ToString() + nl; } |
| 381 | if (action == "sort") { Pretty(doc, sb, 0, indent, true, nl); return sb.ToString() + nl; } |
| 382 | if (action == "compact") { Compact(doc, sb); return sb.ToString() + nl; } |
| 383 | if (action == "to-lines") |
| 384 | { |
| 385 | if (doc.Kind != 2) throw new ParseError("to-lines 需要顶层是数组", 0); |
| 386 | for (int i = 0; i < doc.Items.Count; i++) |
| 387 | { |
| 388 | if (i > 0) sb.Append(nl); |
| 389 | Compact(doc.Items[i], sb); |
| 390 | } |
| 391 | if (doc.Items.Count > 0) sb.Append(nl); |
| 392 | return sb.ToString(); |
| 393 | } |
| 394 | throw new ParseError("未知动作:" + action, 0); |
| 395 | } |
| 396 | |
| 397 | public static string LineCol(string text, int pos) |
| 398 | { |
| 399 | int line = 1, col = 1; |
| 400 | int limit = Math.Min(pos, text.Length); |
| 401 | for (int i = 0; i < limit; i++) |
| 402 | { |
| 403 | if (text[i] == '\n') { line++; col = 1; } |
| 404 | else col++; |
| 405 | } |
| 406 | return line + " 行第 " + col + " 列"; |
| 407 | } |
| 408 | } |
| 409 | } |
| 410 | '@ -Language CSharp |
| 411 | } |
| 412 | |
| 413 | # ---------------- 读入 ---------------- |
| 414 | $isStdin = ($Path -eq '-') |
| 415 | $sourceText = '' |
| 416 | $hasBom = $false |
| 417 | $newline = "`n" |
| 418 | |
| 419 | try { |
| 420 | if ($isStdin) { |
| 421 | if ($InPlace) { throw 'STDIN 输入不能配合 -InPlace' } |
| 422 | $stdin = [Console]::In.ReadToEnd() |
| 423 | if ($null -ne $stdin) { $sourceText = $stdin } |
| 424 | } |
| 425 | else { |
| 426 | if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "文件不存在:$Path" } |
| 427 | $resolved = (Resolve-Path -LiteralPath $Path).Path |
| 428 | $bytes = [System.IO.File]::ReadAllBytes($resolved) |
| 429 | if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $hasBom = $true } |
| 430 | $sourceText = [System.Text.Encoding]::UTF8.GetString($bytes, 0, $bytes.Length).TrimStart([char]0xFEFF) |
| 431 | if ($InPlace -and $OutFile) { throw '-InPlace 与 -OutFile 不能同时使用' } |
| 432 | } |
| 433 | } |
| 434 | catch { |
| 435 | [Console]::Error.WriteLine("参数或文件问题:" + $_.Exception.Message) |
| 436 | exit 3 |
| 437 | } |
| 438 | |
| 439 | if ($sourceText.Contains("`r`n")) { $newline = "`r`n" } |
| 440 | |
| 441 | # ---------------- 处理 ---------------- |
| 442 | try { |
| 443 | $resultText = [JsonTidy.Core]::Run($sourceText, $Action, $Indent, $newline) |
| 444 | } |
| 445 | catch [JsonTidy.ParseError] { |
| 446 | $ex = $_.Exception |
| 447 | if ($ex.Pos -lt 0) { |
| 448 | [Console]::Error.WriteLine("JSON 语法错误:" + $ex.Message) |
| 449 | } |
| 450 | else { |
| 451 | $where = [JsonTidy.Core]::LineCol($sourceText, $ex.Pos) |
| 452 | [Console]::Error.WriteLine("JSON 语法错误:第 $where," + $ex.Message) |
| 453 | } |
| 454 | exit 2 |
| 455 | } |
| 456 | catch { |
| 457 | [Console]::Error.WriteLine("处理失败:" + $_.Exception.Message) |
| 458 | exit 2 |
| 459 | } |
| 460 | |
| 461 | # ---------------- 写出 ---------------- |
| 462 | function Write-Utf8([string]$target, [string]$text, [bool]$withBom) { |
| 463 | $enc = [System.Text.UTF8Encoding]::new($false) |
| 464 | $body = $enc.GetBytes($text) |
| 465 | if ($withBom) { |
| 466 | $bom = [byte[]](0xEF, 0xBB, 0xBF) |
| 467 | $all = [byte[]]::new($bom.Length + $body.Length) |
| 468 | [Array]::Copy($bom, 0, $all, 0, $bom.Length) |
| 469 | [Array]::Copy($body, 0, $all, $bom.Length, $body.Length) |
| 470 | [System.IO.File]::WriteAllBytes($target, $all) |
| 471 | } |
| 472 | else { |
| 473 | [System.IO.File]::WriteAllBytes($target, $body) |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | try { |
| 478 | if ($InPlace) { |
| 479 | $resolved = (Resolve-Path -LiteralPath $Path).Path |
| 480 | Write-Utf8 $resolved $resultText $hasBom |
| 481 | Write-Output ("已写回:" + $resolved) |
| 482 | } |
| 483 | elseif ($OutFile) { |
| 484 | if ([System.IO.Path]::IsPathRooted($OutFile)) { |
| 485 | $full = [System.IO.Path]::GetFullPath($OutFile) |
| 486 | } |
| 487 | else { |
| 488 | $full = [System.IO.Path]::GetFullPath((Join-Path (Get-Location).ProviderPath $OutFile)) |
| 489 | } |
| 490 | Write-Utf8 $full $resultText $false |
| 491 | Write-Output ("已写入:" + $full) |
| 492 | } |
| 493 | else { |
| 494 | Write-Output $resultText.TrimEnd() |
| 495 | } |
| 496 | } |
| 497 | catch { |
| 498 | [Console]::Error.WriteLine("写出结果失败:" + $_.Exception.Message) |
| 499 | exit 3 |
| 500 | } |
| 501 | exit 0 |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

