gjson

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2025 License: MIT Imports: 11 Imported by: 0

README

gjson 包

简介

gjson 包提供了强大的 JSON 解析和操作功能,基于 tidwall/gjson 和 tidwall/sjson 封装,支持快速查询、修改和遍历 JSON 数据。

功能特性

  • 快速查询:使用路径语法快速查询 JSON 值
  • 类型转换:自动转换为各种 Go 类型
  • 修改 JSON:动态修改 JSON 数据
  • 数组遍历:便捷的数组和对象遍历
  • JSON Lines:支持 JSON Lines 格式

安装

go get github.com/snail007/gmc/util/json

快速开始

基本查询
package main

import (
    "fmt"
    "github.com/snail007/gmc/util/json"
)

func main() {
    json := `{
        "name": "John",
        "age": 30,
        "address": {
            "city": "New York",
            "zip": "10001"
        }
    }`
    
    // 获取值
    name := gjson.Get(json, "name")
    fmt.Println(name.String()) // John
    
    age := gjson.Get(json, "age")
    fmt.Println(age.Int()) // 30
    
    city := gjson.Get(json, "address.city")
    fmt.Println(city.String()) // New York
}
数组查询
package main

import (
    "fmt"
    "github.com/snail007/gmc/util/json"
)

func main() {
    json := `{
        "users": [
            {"name": "Alice", "age": 25},
            {"name": "Bob", "age": 30},
            {"name": "Charlie", "age": 35}
        ]
    }`
    
    // 获取数组元素
    first := gjson.Get(json, "users.0.name")
    fmt.Println(first.String()) // Alice
    
    // 获取数组长度
    users := gjson.Get(json, "users")
    fmt.Println("Length:", users.Len()) // 3
    
    // 遍历数组
    users.ForEach(func(key, value gjson.Result) bool {
        fmt.Printf("%s: %d\n", value.Get("name").String(), value.Get("age").Int())
        return true // 继续遍历
    })
}
修改 JSON
package main

import (
    "fmt"
    "github.com/snail007/gmc/util/json"
)

func main() {
    json := `{"name":"John","age":30}`
    
    // 设置值
    result, _ := gjson.Set(json, "age", 31)
    fmt.Println(result) // {"name":"John","age":31}
    
    // 添加新字段
    result, _ = gjson.Set(result, "city", "New York")
    fmt.Println(result) // {"name":"John","age":31,"city":"New York"}
    
    // 删除字段
    result, _ = gjson.Delete(result, "age")
    fmt.Println(result) // {"name":"John","city":"New York"}
}
类型转换
package main

import (
    "fmt"
    "github.com/snail007/gmc/util/json"
)

func main() {
    json := `{
        "string": "hello",
        "int": 42,
        "float": 3.14,
        "bool": true,
        "array": [1, 2, 3],
        "object": {"key": "value"}
    }`
    
    fmt.Println(gjson.Get(json, "string").String())
    fmt.Println(gjson.Get(json, "int").Int())
    fmt.Println(gjson.Get(json, "float").Float())
    fmt.Println(gjson.Get(json, "bool").Bool())
    fmt.Println(gjson.Get(json, "array").Array())
    fmt.Println(gjson.Get(json, "object").Map())
}

API 参考

查询函数
  • Get(json, path) Result:获取 JSON 值
  • GetBytes(json, path) Result:从字节数组获取
  • GetMany(json, ...paths) []Result:获取多个值
  • Parse(json) Result:解析整个 JSON
修改函数
  • Set(json, path, value) (string, error):设置值
  • SetBytes(json, path, value) ([]byte, error):设置值(字节)
  • Delete(json, path) (string, error):删除字段
  • DeleteBytes(json, path) ([]byte, error):删除字段(字节)
验证函数
  • Valid(json) bool:验证 JSON 是否有效
  • ValidBytes(json) bool:验证字节数组 JSON
Result 方法
  • String() string
  • Int() int
  • Int64() int64
  • Float() float64
  • Bool() bool
  • Array() []Result
  • Map() map[string]Result
  • Exists() bool
  • Type() Type
  • ForEach(func(key, value Result) bool)

路径语法

// 基本路径
"name"
"address.city"
"users.0.name"

// 数组索引
"items.0"      // 第一个元素
"items.-1"     // 最后一个元素

// 通配符
"users.*.name" // 所有用户的 name

// 查询
"users.#.name"              // 所有 name 数组
"users.#(age>25).name"      // age > 25 的 name
"users.#(name%\"*li*\")#"   // name 包含 "li" 的数量

// 修饰符
"@reverse"     // 反转数组
"@ugly"        // 压缩 JSON
"@pretty"      // 格式化 JSON

使用场景

  1. 配置文件:解析 JSON 配置
  2. API 响应:处理 HTTP API 返回的 JSON
  3. 数据提取:从复杂 JSON 提取特定字段
  4. JSON 转换:修改 JSON 结构
  5. 日志解析:解析 JSON 格式的日志

注意事项

  1. 路径不存在时返回空 Result
  2. 类型转换失败返回零值
  3. Set/Delete 会创建新的 JSON 字符串
  4. 性能优于标准库的 encoding/json

相关链接

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// AddModifier binds a custom modifier command to the GJSON syntax.
	// This operation is not thread safe and should be executed prior to
	// using all other gjson function.
	AddModifier = gjson.AddModifier

	// ModifierExists returns true when the specified modifier exists.
	ModifierExists = gjson.ModifierExists

	// Escape returns an escaped path component.
	//
	//	json := `{
	//	  "user":{
	//	     "first.name": "Janet",
	//	     "last.name": "Prichard"
	//	   }
	//	}`
	//	user := gjson.Get(json, "user")
	//	println(user.Get(gjson.Escape("first.name"))
	//	println(user.Get(gjson.Escape("last.name"))
	//	// Output:
	//	// Janet
	//	// Prichard
	Escape = gjson.Escape

	// ForEachLine iterates through lines of JSON as specified by the JSON Lines
	// format (http://jsonlines.org/).
	// Each line is returned as a GJSON Result.
	ForEachLine = gjson.ForEachLine

	// Parse parses the json and returns a result.
	//
	// This function expects that the json is well-formed, and does not validate.
	// Invalid json will not panic, but it may return back unexpected results.
	// If you are consuming JSON from an unpredictable source then you may want to
	// use the Valid function first.
	Parse = func(json string) Result {
		r := gjson.Parse(json)
		return Result{
			Result: r,
			path:   r.Path(json),
			paths:  r.Paths(json),
		}
	}
	// ParseBytes parses the json and returns a result.
	// If working with bytes, this method preferred over Parse(string(data))
	ParseBytes = gjson.ParseBytes

	// Valid returns true if the input is valid json.
	//
	//	if !gjson.Valid(json) {
	//		return errors.New("invalid json")
	//	}
	//	value := gjson.Get(json, "name.last")
	Valid = gjson.Valid

	// ValidBytes returns true if the input is valid json.
	//
	//	if !gjson.Valid(json) {
	//		return errors.New("invalid json")
	//	}
	//	value := gjson.Get(json, "name.last")
	//
	// If working with bytes, this method preferred over ValidBytes(string(data))
	ValidBytes = gjson.ValidBytes
)

Functions

This section is empty.

Types

type Builder

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

func NewBuilder

func NewBuilder(v interface{}) *Builder

func NewBuilderE

func NewBuilderE(v interface{}) (*Builder, error)

func (*Builder) Delete

func (s *Builder) Delete(path string) error

Delete deletes a value from json for the specified path. path syntax: https://github.com/tidwall/sjson?tab=readme-ov-file#path-syntax

func (*Builder) Get

func (s *Builder) Get(path string) Result

Get searches json for the specified path. A path is in dot syntax, such as "name.last" or "age". When the value is found it's returned immediately.

A path is a series of keys separated by a dot. A key may contain special wildcard characters '*' and '?'. To access an array value use the index as the key. To get the number of elements in an array or to access a child path, use the '#' character. The dot and wildcard character can be escaped with '\'.

{
  "name": {"first": "Tom", "last": "Anderson"},
  "age":37,
  "children": ["Sara","Alex","Jack"],
  "friends": [
    {"first": "James", "last": "Murphy"},
    {"first": "Roger", "last": "Craig"}
  ]
}
"name.last"          >> "Anderson"
"age"                >> 37
"children"           >> ["Sara","Alex","Jack"]
"children.#"         >> 3
"children.1"         >> "Alex"
"child*.2"           >> "Jack"
"c?ildren.0"         >> "Sara"
"friends.#.first"    >> ["James","Roger"]

This function expects that the json is well-formed, and does not validate. Invalid json will not panic, but it may return back unexpected results. If you are consuming JSON from an unpredictable source then you may want to use the Valid function first. path syntax: https://github.com/tidwall/gjson/blob/master/SYNTAX.md

func (*Builder) GetMany

func (s *Builder) GetMany(path ...string) []Result

GetMany searches json for the multiple paths. The return value is a Result array where the number of items will be equal to the number of input paths.

func (*Builder) Interface

func (s *Builder) Interface() (v interface{})

Interface convert the *Builder to Go DATA,

func (*Builder) JSONArray

func (s *Builder) JSONArray() *JSONArray

JSONArray convert the *Builder to *JSONArray, if the *Builder is not a json array, nil returned.

func (*Builder) JSONObject

func (s *Builder) JSONObject() *JSONObject

JSONObject convert the *Builder to *JSONObject, if the *Builder is not a json object, nil returned.

func (*Builder) Set

func (s *Builder) Set(path string, value interface{}) error

Set sets a json value for the specified path. A path is in dot syntax, such as "name.last" or "age". This function expects that the json is well-formed, and does not validate. Invalid json will not panic, but it may return back unexpected results. An error is returned if the path is not valid.

A path is a series of keys separated by a dot.

{
  "name": {"first": "Tom", "last": "Anderson"},
  "age":37,
  "children": ["Sara","Alex","Jack"],
  "friends": [
    {"first": "James", "last": "Murphy"},
    {"first": "Roger", "last": "Craig"}
  ]
}
"name.last"          >> "Anderson"
"age"                >> 37
"children.1"         >> "Alex"

path syntax: https://github.com/tidwall/sjson?tab=readme-ov-file#path-syntax

func (*Builder) SetRaw

func (s *Builder) SetRaw(path, value string) error

SetRaw sets a raw json value for the specified path. This function works the same as Set except that the value is set as a raw block of json. This allows for setting premarshalled json objects.

func (*Builder) String

func (s *Builder) String() string

String convert the *Builder to JSON string,

type JSONArray

type JSONArray struct {
	*Builder
}

func NewJSONArray

func NewJSONArray(v interface{}) *JSONArray

NewJSONArray create a *JSONArray form v, if error occurred nil returned. v can be json array content of []byte and string, or any data which json.Marshal can be processed.

func NewJSONArrayE

func NewJSONArrayE(v interface{}) (*JSONArray, error)

NewJSONArrayE create a *JSONArray form v, returned error(if have) v can be json array content of []byte and string, or any data which json.Marshal can be processed.

func (*JSONArray) Append

func (s *JSONArray) Append(values ...interface{}) (err error)

func (*JSONArray) First

func (s *JSONArray) First() Result

func (*JSONArray) Last

func (s *JSONArray) Last() Result

func (*JSONArray) Len

func (s *JSONArray) Len() int64

func (*JSONArray) Merge

func (s *JSONArray) Merge(arr interface{}) (err error)

Merge *JSONArray, JSONArray or any valid slice to s

type JSONObject

type JSONObject struct {
	*Builder
}

func NewJSONObject

func NewJSONObject(v interface{}) *JSONObject

NewJSONObject create a *JSONObject form v, if error occurred nil returned. v can be json object content of []byte and string, or any data which json.Marshal can be processed.

func NewJSONObjectE

func NewJSONObjectE(v interface{}) (*JSONObject, error)

NewJSONObjectE create a *JSONObject form v, returned error(if have) v can be json object content of []byte and string, or any data which json.Marshal can be processed.

type JSONResult

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

func NewResult

func NewResult(d ...interface{}) *JSONResult

NewResult Optional args: code int, message string, data interface{}

func NewResultCtx

func NewResultCtx(ctx gcore.Ctx, d ...interface{}) *JSONResult

NewResultCtx Optional args: code int, message string, data interface{}

func (*JSONResult) Code

func (s *JSONResult) Code() int

func (*JSONResult) Data

func (s *JSONResult) Data() interface{}

func (*JSONResult) DataMap

func (s *JSONResult) DataMap() interface{}

func (*JSONResult) Fail

func (s *JSONResult) Fail(format string, v ...interface{}) (err error)

Fail only worked with NewResultCtx()

func (*JSONResult) Message

func (s *JSONResult) Message() string

func (*JSONResult) Set

func (s *JSONResult) Set(key string, value interface{}) *JSONResult

func (*JSONResult) SetCode

func (s *JSONResult) SetCode(code int) *JSONResult

func (*JSONResult) SetData

func (s *JSONResult) SetData(d interface{}) *JSONResult

func (*JSONResult) SetMessage

func (s *JSONResult) SetMessage(format string, msg ...interface{}) *JSONResult

func (*JSONResult) Success

func (s *JSONResult) Success(d ...interface{}) (err error)

Success only worked with NewResultCtx()

func (*JSONResult) ToJSON

func (s *JSONResult) ToJSON() []byte

func (*JSONResult) WriteTo

func (s *JSONResult) WriteTo(dst io.Writer) (err error)

func (*JSONResult) WriteToCtx

func (s *JSONResult) WriteToCtx(ctx gcore.Ctx) (err error)

type Options

type Options = sjson.Options

type Result

type Result struct {
	gjson.Result
	// contains filtered or unexported fields
}

func (Result) ForEach

func (s Result) ForEach(f func(k, v Result) bool)

func (Result) Path

func (s Result) Path() string

func (Result) Paths

func (s Result) Paths() []string

func (Result) ToJSONArray

func (s Result) ToJSONArray() *JSONArray

func (Result) ToJSONObject

func (s Result) ToJSONObject() *JSONObject

Jump to

Keyboard shortcuts

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