当前位置: 首页 > news >正文

Go语言实战案例-开发一个JSON格式校验工具

在日常开发中,经常会遇到需要校验 JSON 格式是否正确的场景:

  • • 前端调试接口返回数据时
  • • 配置文件是否符合 JSON 格式
  • • 接口 Mock 数据校验

如果 JSON 格式不正确,系统往往会报错甚至崩溃。因此开发一个 命令行 JSON 格式校验工具 非常实用。


一、程序目标

我们要实现一个命令行工具 jsoncheck,支持以下功能:

  1. 1. 校验输入的字符串是否是合法 JSON
  2. 2. 校验指定文件是否是合法 JSON
  3. 3. (可选)格式化 JSON 输出

使用方式:

# 校验字符串
jsoncheck -str='{"name":"Go","version":1}'# 校验文件
jsoncheck -file=config.json# 校验并格式化
jsoncheck -file=config.json -pretty

二、实现思路

  1. 1. 使用 flag 包解析命令行参数
  2. 2. 如果输入是字符串,直接用 json.Unmarshal 校验
  3. 3. 如果输入是文件,先读取文件内容再校验
  4. 4. 如果传入 -pretty,就格式化输出 JSON

三、代码实现

main.go

package mainimport ("encoding/json""flag""fmt""os"
)func main() {// 定义命令行参数strInput := flag.String("str", "", "需要校验的 JSON 字符串")fileInput := flag.String("file", "", "需要校验的 JSON 文件路径")pretty := flag.Bool("pretty", false, "是否格式化输出 JSON")flag.Parse()var data []bytevar err error// 优先处理字符串输入if *strInput != "" {data = []byte(*strInput)} else if *fileInput != "" {data, err = os.ReadFile(*fileInput)if err != nil {fmt.Println("❌ 读取文件失败:", err)return}} else {fmt.Println("用法: jsoncheck -str='{\"key\":\"value\"}' 或 -file=path.json [-pretty]")return}// 校验 JSON 格式var js interface{}if err := json.Unmarshal(data, &js); err != nil {fmt.Println("❌ JSON 格式错误:", err)return}fmt.Println("✅ JSON 格式正确")// 如果需要格式化输出if *pretty {formatted, _ := json.MarshalIndent(js, "", "  ")fmt.Println("格式化后的 JSON:")fmt.Println(string(formatted))}
}

四、运行效果

  1. 1. 校验字符串
    go run main.go -str='{"name":"Go","version":1}'
    输出:
    ✅ JSON 格式正确
  2. 2. 校验错误 JSON
    go run main.go -str='{"name":"Go",}'
    输出:
    ❌ JSON 格式错误: invalid character '}' looking for beginning of object key string
  3. 3. 校验文件并格式化
    go run main.go -file=config.json -pretty
    输出:
    ✅ JSON 格式正确
    格式化后的 JSON:
    {"name": "Go","version": 1
    }

五、总结

这个 JSON 格式校验工具小巧但实用,涵盖了:

  • • 命令行参数解析(flag 包)
  • • JSON 校验(json.Unmarshal)
  • • 文件读取(os.ReadFile)
  • • 格式化输出(json.MarshalIndent)

在实际项目中,你可以将它打包成二进制程序放到 PATH 下,随时用来校验 JSON 文件。



文章转载自:

http://OiqAOsUw.sqyjh.cn
http://7HmdYZ0q.sqyjh.cn
http://eMO4Y4AX.sqyjh.cn
http://y8klLyny.sqyjh.cn
http://EgzeBUZC.sqyjh.cn
http://CjI13WRp.sqyjh.cn
http://pCfLduxe.sqyjh.cn
http://Aq3vOE5s.sqyjh.cn
http://MDGguxBS.sqyjh.cn
http://KvYBKRRl.sqyjh.cn
http://NauLusrN.sqyjh.cn
http://tLaVlS34.sqyjh.cn
http://RvIbkO8c.sqyjh.cn
http://7BknuB64.sqyjh.cn
http://IYT9bYUe.sqyjh.cn
http://n38yHyzP.sqyjh.cn
http://zaa3X0Fj.sqyjh.cn
http://NUlZwhyT.sqyjh.cn
http://y8kf4srx.sqyjh.cn
http://OtheHvgR.sqyjh.cn
http://Z58v5eQe.sqyjh.cn
http://h3AtBMXD.sqyjh.cn
http://S8mcEvWu.sqyjh.cn
http://Kxxw0WGN.sqyjh.cn
http://rnEbJccv.sqyjh.cn
http://cEnljVH6.sqyjh.cn
http://6klfEZpr.sqyjh.cn
http://CAKgyfqV.sqyjh.cn
http://GQCudXNC.sqyjh.cn
http://hcGaknLa.sqyjh.cn
http://www.dtcms.com/a/372873.html

相关文章:

  • AI技术架构与GEO算法原理如何重塑搜索引擎可见性
  • 【AI测试前沿】谷歌Fuzzing安全测试Go语言指南
  • 佰力博检测与您探讨薄膜样品如何测介电常数?
  • jsBridge接入流程
  • TFS-2018《On the convergence of the sparse possibilistic c-means algorithm》
  • ArrayList中的源码解析
  • 详细解析SparkStreaming和Kafka集成的两种方式的区别和优劣
  • 大数据Spark(六十三):RDD-Resilient Distributed Dataset
  • 云原生TodoList Demo 项目,验证云原生核心特性
  • C语言爬虫开发:常见错误与优化方案
  • Linux 应急响应实操 Checklist
  • 【PCIe EP 设备入门学习专栏 -- 8.2.3 Local Bus Controller (LBC) 详细介绍】
  • 将基于 Oracle JDK 17 开发的 Spring Boot 3.2.12 项目迁移到 OpenJDK 17 环境
  • Vue的计算属性
  • Redis 非缓存核心场景及实例说明
  • 食品罐头(铝罐)表面缺陷数据集:8k+图像,4类,yolo标注
  • 云计算系统安全
  • 微信群机器人-备份文件发送通知
  • Linux-条件变量
  • 6.python——字符串
  • 懒汉式——LazyMan(任务队列应用)
  • Nginx 实战系列(四)—— Nginx反向代理与负载均衡实战指南
  • Nginx 反向代理 + Tomcat 集群:负载均衡配置步骤与核心原理
  • 【Linux】匿名管道和进程池
  • PWA:打造媲美 Native Apps 的 Web 应用体验
  • # 小程序 Web 登录流程完整解析
  • 2025中国AI HR市场深度洞察:趋势、厂商与未来展望
  • 并发编程的守护者:信号量与日志策略模式解析
  • Flink Task线程处理模型:Mailbox
  • ActiveMQ classic ,artemis ,artemis console ,nms clients,cms client详解