leptjson

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 16, 2025 License: MIT Imports: 15 Imported by: 0

README

从零开始的 JSON 库教程(十六):命令行工具实现

命令行工具简介

在本章中,我们为 leptjson 库添加了命令行工具功能,使用户能够通过简单的命令行操作来处理和分析 JSON 数据。这个命令行工具提供了多种实用功能,如 JSON 解析、格式化、最小化、统计分析、路径查询和文档比较,大大提高了处理 JSON 数据的效率。

主要功能

  • 解析 (parse): 验证 JSON 文件的格式是否合法
  • 格式化 (format): 将 JSON 文件格式化,添加适当的缩进和换行,提高可读性
  • 最小化 (minify): 移除 JSON 文件中的所有不必要的空格,减小文件大小
  • 统计 (stats): 分析 JSON 文件,提供各种统计信息,如对象数量、数组数量、嵌套深度等
  • 查找 (find): 使用简化的路径表达式在 JSON 文件中查找特定数据
  • JSONPath (path): 使用完整的 JSONPath 语法在 JSON 文件中查询数据,支持复杂查询和过滤条件
  • 比较 (compare): 比较两个 JSON 文件,查找它们之间的差异
  • 验证 (validate): 使用 JSON Schema 验证 JSON 文件的结构和内容
  • 指针操作 (pointer): 使用 JSON Pointer 定位和操作 JSON 文档中的值
  • 补丁应用 (patch): 使用 JSON Patch 对 JSON 文档应用一系列修改操作
  • 合并补丁 (merge-patch): 使用 JSON Merge Patch 简化的方式合并 JSON 文档

使用方法

使用格式: leptjson [选项] 命令 [参数]

全局选项
  • --help, -h: 显示帮助信息
  • --verbose, -v: 显示详细输出
  • --version: 显示版本信息
命令详解
parse - 解析并验证 JSON 文件
leptjson parse data.json

此命令将验证 data.json 文件是否是有效的 JSON 格式。如果文件有格式错误,将显示详细的错误信息。

format - 格式化 JSON 文件
leptjson format --indent=2 data.json formatted.json

data.json 格式化并保存为 formatted.json,使用 2 个空格作为缩进。如果不指定输出文件,将自动创建一个 .formatted.json 后缀的文件。

minify - 最小化 JSON 文件
leptjson minify data.json data.min.json

移除 data.json 中的所有空白字符,创建一个紧凑的 data.min.json 文件。

stats - 显示 JSON 统计信息
leptjson stats data.json

分析 data.json 文件并显示统计信息,包括:

  • 文件大小
  • 最大嵌套深度
  • 对象数量
  • 数组数量
  • 键总数和最长键
  • 字符串、数字、布尔值和 null 值的数量

可以使用 --json 选项以 JSON 格式输出统计信息:

leptjson stats --json data.json
find - 查找 JSON 路径
leptjson find data.json "$.store.book[0].title"

使用 JSONPath 表达式 $.store.book[0].titledata.json 中查找匹配的值。

可以使用 --output 选项指定输出格式:

  • compact: 紧凑 JSON(默认)
  • pretty: 格式化 JSON
  • raw: 对于简单值,仅输出值本身
leptjson find --output=pretty data.json "$.store.book[*]"
path - 使用 JSONPath 查询 JSON 数据
leptjson path [选项] 文件 JSONPATH表达式

使用完整的 JSONPath 语法从 JSON 文件中提取数据。相比 find 命令,path 命令支持更强大的查询功能。

选项:

  • --output=FORMAT: 设置输出格式,可选值有 compact (紧凑), pretty (美化), raw (原始), table (表格)
  • --all: 显示所有匹配结果(默认只显示前10个)
  • --csv=FILE: 将结果保存为 CSV 文件
  • --no-path: 不在输出中显示路径信息

支持的 JSONPath 语法:

  • $: 根对象
  • .property: 子属性访问
  • ['property']: 带引号的属性访问
  • [index]: 数组索引访问
  • [start:end:step]: 数组切片
  • *: 通配符,匹配所有成员
  • ..property: 递归下降,匹配任意深度的属性
  • [?(@.prop > 10)]: 过滤表达式
  • [?(@.prop)]: 存在性检查
  • [?(@.name == 'value')]: 相等性检查
  • ['a','b']: 多属性选择

示例:

# 查找所有书籍的作者
leptjson path books.json "$.store.book[*].author"

# 查询价格小于10的所有书籍
leptjson path --output=table books.json "$..book[?(@.price < 10)]"

# 查找所有价格并导出为CSV
leptjson path --csv=prices.csv books.json "$..price"

# 递归查找所有ID
leptjson path users.json "$..id"
compare - 比较两个 JSON 文件
leptjson compare file1.json file2.json

比较 file1.jsonfile2.json,显示它们之间的所有差异,包括类型不匹配、值不同和缺失/额外的键。

可以使用 --json 选项以 JSON 格式输出差异:

leptjson compare --json file1.json file2.json
validate - 使用 JSON Schema 验证 JSON 文件
leptjson validate schema.json data.json

使用 schema.json 中定义的 JSON Schema 验证 data.json 文件。如果验证失败,将显示详细的错误信息,包括验证失败的位置和原因。

可以使用 --format 选项指定输出格式:

  • text: 人类可读的文本格式(默认)
  • json: 机器可读的 JSON 格式
leptjson validate --format=json schema.json data.json
pointer - 使用 JSON Pointer 操作 JSON 文件
leptjson pointer data.json "/users/0/name"

使用 JSON Pointer (RFC 6901) 查找 data.json 中位于路径 /users/0/name 的值。

可以使用 --operation 选项指定操作类型:

  • get: 获取值(默认)
  • add: 添加或替换值
  • remove: 删除值
  • replace: 替换值

对于 addreplace 操作,需要使用 --value 选项指定要设置的值:

leptjson pointer --operation=replace --value="John" data.json "/users/0/name"

对于修改操作,可以使用 --output 选项指定输出文件,默认会覆盖原文件:

leptjson pointer --operation=add --value="admin" --output=new.json data.json "/users/0/role"
patch - 使用 JSON Patch 应用修改
leptjson patch patch.json data.json output.json

patch.json 中定义的 JSON Patch 操作应用到 data.json,并将结果保存到 output.json

JSON Patch (RFC 6902) 支持以下操作:

  • add: 添加值
  • remove: 删除值
  • replace: 替换值
  • move: 移动值
  • copy: 复制值
  • test: 测试值是否匹配

可以使用 --test 选项仅测试补丁是否可以应用,而不实际修改文件:

leptjson patch --test patch.json data.json

使用 --in-place 选项直接修改原文件,而不是创建新文件:

leptjson patch --in-place patch.json data.json
merge-patch - 使用 JSON Merge Patch 合并文档
leptjson merge-patch patch.json data.json output.json

patch.json 中定义的 JSON Merge Patch 应用到 data.json,并将结果保存到 output.json

JSON Merge Patch (RFC 7396) 是一种比 JSON Patch 更简单的 JSON 文档合并方式,其主要规则:

  • 如果补丁中的值为 null,则从目标中删除该字段
  • 如果补丁中的值不为 null,则替换目标中的对应字段
  • 如果两边都是对象,则递归合并
  • 对于数组,直接替换而不是合并

使用 --in-place 选项直接修改原文件,而不是创建新文件:

leptjson merge-patch --in-place changes.json data.json

使用示例

解析并格式化 JSON 文件
# 验证 JSON 文件
leptjson parse data.json

# 格式化 JSON 文件
leptjson format --indent=4 data.json pretty.json

# 最小化 JSON 文件
leptjson minify pretty.json data.min.json
分析和验证 JSON 文件
# 获取 JSON 统计信息
leptjson stats data.json

# 验证 JSON 是否符合 Schema
leptjson validate user-schema.json user.json

# 查找特定数据
leptjson find data.json "$.users[?(@.age>30)].name"

# 比较两个 JSON 文件
leptjson compare original.json updated.json
修改 JSON 文件
# 使用 JSON Pointer 修改特定值
leptjson pointer --operation=replace --value=true data.json "/user/active"

# 使用 JSON Patch 应用多个修改
leptjson patch updates.json data.json data-updated.json

# 使用 JSON Merge Patch 合并文档
leptjson merge-patch merge.json data.json data-merged.json
复杂查询示例
# 使用JSONPath查询所有价格小于10的书籍,以表格形式显示
leptjson path --output=table library.json "$..book[?(@.price < 10)]"

# 使用JSONPath递归查找所有作者并保存为CSV文件
leptjson path --csv=authors.csv library.json "$..author"

# 使用JSON Pointer访问特定路径
leptjson pointer users.json "/users/0/name"

实现细节

命令行工具使用 Go 标准库的 flag 包实现命令行参数解析,并利用我们在前面章节中实现的 JSON 解析、序列化、JSONPath、JSON Schema、JSON Pointer 和 JSON Patch 功能。主要组件包括:

  1. JSON 解析器: 使用我们的 Parse 函数验证 JSON 文件
  2. 格式化器: 实现了带缩进的 JSON 输出
  3. 统计分析器: 递归遍历 JSON 结构,计算各种统计信息
  4. JSONPath 查询器: 使用我们的 JSONPath 实现查找指定路径的值
  5. 比较器: 递归比较两个 JSON 结构,检测所有差异
  6. JSON Schema 验证器: 实现 JSON Schema 验证功能
  7. JSON Pointer 处理器: 实现 RFC 6901 定义的 JSON Pointer 功能
  8. JSON Patch 应用器: 实现 RFC 6902 定义的 JSON Patch 功能

测试

go-json-tutorial/tutorial16 目录下运行测试:

go test

构建和安装

go-json-tutorial/tutorial16/main 目录下构建命令行工具:

go build -o leptjson

或使用 go install 安装到系统路径:

go install

参考资料

Documentation

Overview

cycle_detection.go - 循环引用检测实现

json_patch.go - JSON Patch 实现 (RFC 6902)

json_path.go - JSON Path 实现

json_pointer.go - JSON指针实现 (RFC6901)

json_schema.go - JSON Schema 验证实现(基于部分 JSON Schema Draft 7)

leptjson.go - Go语言版JSON库

Index

Constants

View Source
const (
	OpAdd     = "add"
	OpRemove  = "remove"
	OpReplace = "replace"
	OpMove    = "move"
	OpCopy    = "copy"
	OpTest    = "test"
)

JSON Patch操作类型

View Source
const Version = "1.0.0"

命令行工具的版本号

Variables

This section is empty.

Functions

func BuildJSONPointer

func BuildJSONPointer(segments ...interface{}) (string, error)

BuildJSONPointer 创建一个JSON指针字符串

func ClearArray

func ClearArray(v *Value)

ClearArray 清空数组的所有元素

func ClearObject

func ClearObject(v *Value)

ClearObject 清空对象的所有成员

func Copy

func Copy(dst, src *Value)

Copy 深度复制一个JSON值

func CopySafe

func CopySafe(dst, src *Value) error

CopySafe 安全复制JSON值,避免循环引用

func CopySafeWithReplacement

func CopySafeWithReplacement(dst, src *Value)

CopySafeWithReplacement 带替换的安全复制

func CustomCopySafeWithReplacement

func CustomCopySafeWithReplacement(dst, src *Value, replacer CircularReplacer)

CustomCopySafeWithReplacement 使用自定义替换器的安全复制

func Equal

func Equal(lhs, rhs *Value) bool

Equal 判断两个JSON值是否相等

func EraseArrayElement

func EraseArrayElement(v *Value, index, count int)

EraseArrayElement 删除数组中从index开始的count个元素

func FindObjectIndex

func FindObjectIndex(v *Value, key string) int

FindObjectIndex 查找JSON对象中指定键的索引

func Free

func Free(v *Value)

Free 释放JSON值占用的资源

func GetArrayCapacity

func GetArrayCapacity(v *Value) int

GetArrayCapacity 获取数组当前的容量

func GetArraySize

func GetArraySize(v *Value) int

GetArraySize 获取JSON数组的大小

func GetBoolean

func GetBoolean(v *Value) bool

GetBoolean 获取JSON布尔值

func GetErrorMessage

func GetErrorMessage(code ParseError) string

GetErrorMessage 根据错误码获取错误消息

func GetNumber

func GetNumber(v *Value) float64

GetNumber 获取JSON数字值

func GetObjectCapacity

func GetObjectCapacity(v *Value) int

GetObjectCapacity 获取对象的容量

func GetObjectKey

func GetObjectKey(v *Value, index int) string

GetObjectKey 获取JSON对象的键

func GetObjectSize

func GetObjectSize(v *Value) int

GetObjectSize 获取JSON对象的大小

func GetString

func GetString(v *Value) string

GetString 获取JSON字符串值

func HasCycle

func HasCycle(v *Value) bool

HasCycle 检测JSON值中是否存在循环引用

func Marshal

func Marshal(v interface{}) (string, error)

Marshal 将 Go 值序列化为 JSON 字符串,支持 struct tag。

func Move

func Move(dst, src *Value)

Move 将源值移动到目标值,并将源值设为null

func ParseJSONPointer

func ParseJSONPointer(pointer string) (*JSONPointer, JSONPointerError)

ParseJSONPointer 解析JSON指针字符串 例如: "/foo/0/bar" => ["foo", "0", "bar"]

func PointerAdd

func PointerAdd(doc *Value, pointer *CliJSONPointer, value *Value) error

执行添加操作

func PointerRemove

func PointerRemove(doc *Value, pointer *CliJSONPointer) error

执行删除操作

func PointerReplace

func PointerReplace(doc *Value, pointer *CliJSONPointer, value *Value) error

执行替换操作

func PopBackArrayElement

func PopBackArrayElement(v *Value)

PopBackArrayElement 移除数组末尾的元素

func RemoveObjectValue

func RemoveObjectValue(v *Value, index int)

RemoveObjectValue 移除对象中指定索引的成员

func RemoveObjectValueByKey

func RemoveObjectValueByKey(v *Value, key string) bool

RemoveObjectValueByKey 是一个辅助函数,需要添加到 leptjson.go 或在此处实现 它根据键来查找并删除对象成员

func RemoveValueByPointer

func RemoveValueByPointer(v *Value, pointerStr string) error

RemoveValueByPointer 使用JSON指针删除值

func ReserveArray

func ReserveArray(v *Value, capacity int)

ReserveArray 扩充数组容量

func ReserveObject

func ReserveObject(v *Value, capacity int)

ReserveObject 扩充对象容量

func ResolvePointer

func ResolvePointer(doc *Value, pointer *CliJSONPointer) (*Value, []*Value, error)

解析JSON Pointer并返回引用的值

func RunCLI

func RunCLI()

RunCLI 运行CLI,处理命令行参数和子命令

func SafeCopyWithReplacer

func SafeCopyWithReplacer(dst, src *Value, replacer CircularReplacer)

SafeCopyWithReplacer 带替换器的安全复制,处理循环引用

func SetArray

func SetArray(v *Value, capacity int)

SetArray 设置值为数组类型,可以预分配容量

func SetBoolean

func SetBoolean(v *Value, b bool)

SetBoolean 设置JSON布尔值

func SetNull

func SetNull(v *Value)

SetNull 将值设置为NULL类型

func SetNumber

func SetNumber(v *Value, n float64)

SetNumber 设置JSON数字值

func SetObject

func SetObject(v *Value)

SetObject 设置值为对象类型,可以预分配容量

func SetString

func SetString(v *Value, s string)

SetString 设置JSON字符串值

func SetValueByPointer

func SetValueByPointer(v *Value, pointerStr string, value *Value) error

SetValueByPointer 使用JSON指针设置值

func ShrinkArray

func ShrinkArray(v *Value)

ShrinkArray 缩小数组容量至实际大小

func ShrinkObject

func ShrinkObject(v *Value)

ShrinkObject 缩小对象容量至实际大小

func Swap

func Swap(lhs, rhs *Value)

Swap 交换两个JSON值

func ValuesEqual

func ValuesEqual(a, b *Value) bool

比较两个值是否相等

Types

type CircularReplacer

type CircularReplacer func(path []string) *Value

CircularReplacer 定义了在发现循环引用时的替换函数类型

type CliJSONPointer

type CliJSONPointer struct {
	Tokens []string
}

JSON Pointer解析器

func NewJSONPointer

func NewJSONPointer(pointer string) (*CliJSONPointer, error)

创建新的JSON Pointer

type CliPatchOperation

type CliPatchOperation struct {
	Op    string `json:"op"`
	Path  string `json:"path"`
	From  string `json:"from,omitempty"`
	Value *Value `json:"value,omitempty"`
}

JSON Patch操作

type CycleError

type CycleError int

CycleError 表示循环引用错误

const (
	CYCLE_OK CycleError = iota
	CYCLE_DETECTED
)

循环引用错误常量

func DetectCycle

func DetectCycle(v *Value) CycleError

DetectCycle 检测JSON值中是否存在循环引用

func SafeCopy

func SafeCopy(dst, src *Value) CycleError

SafeCopy 安全复制JSON值,检测并处理循环引用

func (CycleError) Error

func (e CycleError) Error() string

实现 Error 接口

type EnhancedError

type EnhancedError struct {
	Code          ParseError // 错误码
	Message       string     // 错误消息
	Line          int        // 行号
	Column        int        // 列号
	Context       string     // 错误发生的上下文
	Pointer       string     // 错误位置指针(比如 "----^")
	SourceInput   string     // 输入源
	IsRecoverable bool       // 是否可恢复
}

EnhancedError 定义了一个增强的错误类型,包含详细信息

func (*EnhancedError) Error

func (e *EnhancedError) Error() string

Error 实现error接口

type JSONMergePatch

type JSONMergePatch struct {
	Document *Value
}

JSONMergePatch 表示一个 JSON Merge Patch 文档

func CreateMergePatch

func CreateMergePatch(source, target *Value) (*JSONMergePatch, error)

CreateMergePatch 创建从源文档到目标文档的 JSON Merge Patch (*Value) 返回一个表示变更的 JSONMergePatch 对象

func NewJSONMergePatch

func NewJSONMergePatch(patchDoc *Value) (*JSONMergePatch, error)

NewJSONMergePatch 从 *Value 创建 JSON Merge Patch 对象 注意:Merge Patch 本身必须是有效的 JSON,由调用方保证

func (*JSONMergePatch) Apply

func (p *JSONMergePatch) Apply(target *Value) (*Value, error)

Apply 将该 Merge Patch 应用到目标文档 (*Value) 返回修改后的新文档 (*Value),不修改原始文档或 patch 本身。

func (*JSONMergePatch) String

func (p *JSONMergePatch) String() (string, error)

String 返回 JSON Merge Patch 的字符串表示

type JSONPatch

type JSONPatch struct {
	Operations []PatchOperation // 操作列表
}

JSONPatch 表示一个 JSON Patch 文档,包含多个操作

func CreatePatch

func CreatePatch(source, target *Value) (*JSONPatch, error)

CreatePatch 生成从 source 到 target 的 JSON Patch

func NewJSONPatch

func NewJSONPatch(patchDoc *Value) (*JSONPatch, error)

NewJSONPatch 从 JSON 值中创建 JSON Patch 对象

func NewJSONPatchFromString

func NewJSONPatchFromString(patchStr string) (*JSONPatch, error)

NewJSONPatchFromString 从 JSON 字符串创建 JSON Patch 对象

func (*JSONPatch) Apply

func (p *JSONPatch) Apply(doc *Value) error

Apply 将 JSON Patch 应用到文档

func (*JSONPatch) String

func (p *JSONPatch) String() (string, error)

String 返回 JSON Patch 的字符串表示

type JSONPath

type JSONPath struct {
	Path   string  // 原始路径表达式
	Tokens []Token // 令牌列表
}

JSONPath 表示一个解析后的 JSON Path 表达式

func NewJSONPath

func NewJSONPath(path string) (*JSONPath, error)

NewJSONPath 解析 JSON Path 表达式并创建一个 JSONPath 对象

func (*JSONPath) Query

func (jp *JSONPath) Query(doc *Value) ([]*Value, error)

Query 使用 JSON Path 查询 JSON 值并返回匹配的值列表

func (*JSONPath) QueryOne

func (jp *JSONPath) QueryOne(doc *Value) (*Value, error)

QueryOne 返回第一个匹配的值,如果没有匹配则返回 nil

type JSONPathError

type JSONPathError struct {
	Path    string // JSON Path 表达式
	Message string // 错误消息
	Index   int    // 错误发生的位置
}

JSONPathError 表示解析或执行 JSON Path 时的错误

func (JSONPathError) Error

func (e JSONPathError) Error() string

Error 实现 error 接口

type JSONPointer

type JSONPointer struct {
	// contains filtered or unexported fields
}

JSONPointer 表示一个JSON指针(RFC6901)

func GetJSONPointer

func GetJSONPointer(segments ...interface{}) (*JSONPointer, error)

GetJSONPointer 创建一个指向指定路径的JSONPointer 例如: NewJSONPointer("foo", 0, "bar") => "/foo/0/bar"

func (*JSONPointer) Get

func (p *JSONPointer) Get(root *Value) (*Value, JSONPointerError)

Get 根据JSON指针获取值

func (*JSONPointer) Insert

func (p *JSONPointer) Insert(root *Value, value *Value) JSONPointerError

Insert 根据JSON指针在数组中插入值或在对象中添加/替换值 对于数组,支持索引插入和末尾追加 ("-")

func (*JSONPointer) Remove

func (p *JSONPointer) Remove(root *Value) JSONPointerError

Remove 根据JSON指针删除值

func (*JSONPointer) Replace

func (p *JSONPointer) Replace(root *Value, value *Value) JSONPointerError

Replace 根据JSON指针替换现有值或添加对象成员 注意:对于数组,此方法执行替换,不执行插入。

func (*JSONPointer) String

func (p *JSONPointer) String() string

创建一个JSON指针字符串表示

type JSONPointerError

type JSONPointerError int

JSONPointerError 表示JSON指针相关错误

const (
	POINTER_OK JSONPointerError = iota
	POINTER_INVALID_FORMAT
	POINTER_INDEX_OUT_OF_RANGE
	POINTER_KEY_NOT_FOUND
	POINTER_INVALID_TARGET
)

JSON指针错误常量

func (JSONPointerError) Error

func (e JSONPointerError) Error() string

实现 Error 接口

type JSONSchema

type JSONSchema struct {
	Schema *Value // 存储 JSON Schema 的 Value 对象
}

JSONSchema 表示一个 JSON Schema 对象

func NewJSONSchema

func NewJSONSchema(schemaJSON string) (*JSONSchema, error)

NewJSONSchema 创建一个新的 JSON Schema

func NewJSONSchemaFromValue

func NewJSONSchemaFromValue(schema *Value) (*JSONSchema, error)

NewJSONSchemaFromValue 从 Value 对象创建 JSON Schema

func (*JSONSchema) Validate

func (js *JSONSchema) Validate(data *Value) *SchemaValidationResult

Validate 根据 Schema 验证 JSON 数据

type JSONStats

type JSONStats struct {
	TotalSize    int64  // 文件总大小(字节)
	ObjectCount  int    // 对象数量
	ArrayCount   int    // 数组数量
	StringCount  int    // 字符串数量
	NumberCount  int    // 数字数量
	BooleanCount int    // 布尔值数量
	NullCount    int    // null值数量
	MaxDepth     int    // 最大嵌套深度
	KeyCount     int    // 键的总数
	MaxKeyLength int    // 最长键的长度
	LongestKey   string // 最长的键
}

统计信息结构

type Member

type Member struct {
	K string // 键
	V *Value // 值
}

Member 表示对象的成员(键值对)

type ParseError

type ParseError int

ParseError 表示解析错误

const (
	PARSE_OK                           ParseError = iota // 解析成功
	PARSE_EXPECT_VALUE                                   // 期望一个值
	PARSE_INVALID_VALUE                                  // 无效的值
	PARSE_ROOT_NOT_SINGULAR                              // 根节点不唯一
	PARSE_NUMBER_TOO_BIG                                 // 数字太大
	PARSE_MISS_QUOTATION_MARK                            // 缺少引号
	PARSE_INVALID_STRING_ESCAPE                          // 无效的转义序列
	PARSE_INVALID_STRING_CHAR                            // 无效的字符
	PARSE_INVALID_UNICODE_HEX                            // 无效的Unicode十六进制
	PARSE_INVALID_UNICODE_SURROGATE                      // 无效的Unicode代理对
	PARSE_MISS_COMMA_OR_SQUARE_BRACKET                   // 缺少逗号或方括号
	PARSE_MISS_KEY                                       // 缺少键
	PARSE_MISS_COLON                                     // 缺少冒号
	PARSE_MISS_COMMA_OR_CURLY_BRACKET                    // 缺少逗号或花括号
	PARSE_MAX_DEPTH_EXCEEDED                             // 超过最大嵌套深度
	PARSE_COMMENT_NOT_CLOSED                             // 注释未闭合
)

解析错误常量

func Parse

func Parse(v *Value, json string) ParseError

Parse 解析JSON文本(使用默认选项)

func ParseWithOptions

func ParseWithOptions(v *Value, json string, options ParseOptions) ParseError

ParseWithOptions 使用自定义选项解析JSON文本

解析步骤: 1. 跳过前导空白字符 2. 解析JSON值 3. 跳过后续空白字符 4. 检查是否还有额外内容(这将导致PARSE_ROOT_NOT_SINGULAR错误)

func (ParseError) Error

func (e ParseError) Error() string

Error 返回解析错误的描述

type ParseOptions

type ParseOptions struct {
	MaxDepth          int  // 最大嵌套深度
	AllowComments     bool // 是否允许注释
	AllowTrailing     bool // 是否允许尾随逗号
	StrictMode        bool // 严格模式(更严格的检查)
	RecoverFromErrors bool // 是否从非致命错误恢复
}

ParseOptions 定义解析选项

func DefaultParseOptions

func DefaultParseOptions() ParseOptions

DefaultParseOptions 返回默认解析选项

type PatchError

type PatchError struct {
	Operation string // 发生错误的操作类型
	Path      string // 发生错误的路径
	Message   string // 错误消息
}

PatchError 表示 JSON Patch 操作中的错误

func (PatchError) Error

func (e PatchError) Error() string

Error 实现 error 接口

type PatchOperation

type PatchOperation struct {
	Op    string // 操作类型: add, remove, replace, move, copy, test
	Path  string // 操作的目标路径 (JSON Pointer)
	From  string // 源路径 (用于 move 和 copy 操作)
	Value *Value // 值 (用于 add, replace 和 test 操作)
}

PatchOperation 表示 JSON Patch 中的单个操作

type SchemaValidationError

type SchemaValidationError struct {
	Path    string // 导致错误的 JSON 路径
	Message string // 错误描述
}

SchemaValidationError 表示 JSON Schema 验证错误

func (SchemaValidationError) Error

func (e SchemaValidationError) Error() string

实现 Error 接口

type SchemaValidationResult

type SchemaValidationResult struct {
	Valid  bool                    // 是否验证通过
	Errors []SchemaValidationError // 验证错误列表
}

SchemaValidationResult 存储验证结果

func (*SchemaValidationResult) AddError

func (r *SchemaValidationResult) AddError(path, message string)

AddError 添加验证错误

type SliceInfo

type SliceInfo struct {
	Start int
	End   int
	Step  int
}

SliceInfo 存储数组切片信息

type StringifyError

type StringifyError int

StringifyError 表示字符串化错误

const (
	STRINGIFY_OK StringifyError = iota // 字符串化成功
)

字符串化错误常量

func Stringify

func Stringify(v *Value) (string, StringifyError)

Stringify 将Value转换为JSON字符串

func (StringifyError) Error

func (e StringifyError) Error() string

Error 返回字符串化错误的描述

type Token

type Token struct {
	Type  TokenType // 令牌类型
	Value string    // 令牌值
}

Token 表示 JSON Path 中的一个令牌

type TokenType

type TokenType int

TokenType 表示 JSON Path 令牌的类型

const (
	ROOT              TokenType = iota // $ - 根节点
	CURRENT                            // @ - 当前节点
	DOT                                // . - 子属性访问
	RECURSIVE_DESCENT                  // .. - 递归下降
	WILDCARD                           // * - 通配符
	BRACKET_START                      // [ - 下标访问开始
	BRACKET_END                        // ] - 下标访问结束
	INDEX                              // 数字索引
	PROPERTY                           // 属性名
	SLICE                              // 切片 [start:end:step]
	UNION                              // 并集 [expr,expr]
	FILTER                             // ?() - 过滤器
)

type ValidationResult

type ValidationResult struct {
	Valid   bool     `json:"valid"`
	Errors  []string `json:"errors,omitempty"`
	Message string   `json:"message,omitempty"`
}

验证结果结构

type Value

type Value struct {
	Type ValueType `json:"type"` // 值类型
	N    float64   `json:"n"`    // 数字值(当Type为NUMBER时有效)
	S    string    `json:"s"`    // 字符串值(当Type为STRING时有效)
	A    []*Value  `json:"a"`    // 数组值(当Type为ARRAY时有效)
	O    []Member  `json:"o"`    // 对象值(当Type为OBJECT时有效)
}

Value 表示一个JSON值

func DefaultCircularReplacer

func DefaultCircularReplacer(path []string) *Value

DefaultCircularReplacer 默认循环引用替换器

func FindObjectKey

func FindObjectKey(v *Value, key string) (*Value, bool)

FindObjectKey 根据键名在对象中查找对应值,如果找到返回值和true,否则返回nil和false

func GetArrayElement

func GetArrayElement(v *Value, index int) *Value

GetArrayElement 获取JSON数组的元素

func GetObjectValue

func GetObjectValue(v *Value, index int) *Value

GetObjectValue 获取JSON对象的值

func GetObjectValueByKey

func GetObjectValueByKey(v *Value, key string) *Value

GetObjectValueByKey 根据键获取JSON对象的值

func GetValueByPointer

func GetValueByPointer(v *Value, pointerStr string) (*Value, error)

GetValueByPointer 使用JSON指针获取值

func InsertArrayElement

func InsertArrayElement(v *Value, index int) *Value

InsertArrayElement 在指定位置插入元素,并返回该元素

func PushBackArrayElement

func PushBackArrayElement(v *Value) *Value

PushBackArrayElement 在数组末尾添加一个新元素,并返回该元素

func QueryOneString

func QueryOneString(doc *Value, path string) (*Value, error)

QueryOneString 是一个便捷函数,返回匹配路径的第一个值

func QueryString

func QueryString(doc *Value, path string) ([]*Value, error)

QueryString 是一个便捷函数,直接使用路径表达式查询 JSON 值

func SetObjectValue

func SetObjectValue(v *Value, key string) *Value

SetObjectValue 设置对象的键值对,如果键已存在则返回其值指针,否则添加新的键值对并返回新值指针

func (Value) String

func (v Value) String() string

String 返回Value的字符串表示

type ValueType

type ValueType int

ValueType 表示JSON值的类型

const (
	NULL ValueType = iota
	FALSE
	TRUE
	NUMBER
	STRING
	ARRAY
	OBJECT
)

JSON值类型常量

func GetType

func GetType(v *Value) ValueType

GetType 获取JSON值的类型

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL