qjson

package module
v0.0.0-...-654840d Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2025 License: MIT Imports: 15 Imported by: 4

README

qjson

CI codecov Go Version

Fast, lightweight JSON encode/decode and query library. It provides an inspectable/mutable JSONTree structure and a powerful QJSON Path query syntax.

Highlights

  • High‑performance parsing: decode raw JSON into traversable JSONTree/Node with object pool reuse to reduce GC pressure.
  • QJSON Path queries: access by object keys and array indexes; support the # selector and filters (==, =, !==, !=, >, >=, <, <=), plus escaped dots in keys.
  • In‑place mutation: set values via SetString/SetInt/SetBool/SetFloat, remove object keys and array elements.
  • Readable output: ANSI colored output via ColorfulMarshal and ColorfulMarshalWithIndent for terminal UX.
  • Encoding interoperability: json.Marshal/Unmarshal works directly on JSONTree; convert any Go object via ConvertToJSONTree.
  • Equality and hashing: structural equality with Equal() and stable hashes with Hash()/Rehash().
  • Diff: Diff() produces a list of differences between two trees, useful for change audits and test comparisons.
  • Zero external dependencies: standard library only (Go ≥ 1.13).

Install

go get -u github.com/qjpcpu/qjson@latest

Quick Start

package main

import (
  "encoding/json"
  "fmt"
  qjson "github.com/qjpcpu/qjson"
)

func main() {
  // Parse
  tree, err := qjson.Decode([]byte(`{"name":{"first":"Tom","last":"Anderson"},"age":37}`))
  if err != nil { panic(err) }

  // Query
  fmt.Println(tree.Find("name.last").AsString()) // Anderson
  fmt.Println(tree.Find("age").AsInt())          // 37

  // Mutate
  tree.Find("name.first").SetString("Link")
  tree.Find("age").SetInt(12)

  // Encode (std lib)
  data, _ := json.Marshal(tree)
  fmt.Println(string(data)) // {"name":{"first":"Link","last":"Anderson"},"age":12}

  // Color output
  fmt.Println(string(tree.ColorfulMarshal()))
}

QJSON Path Syntax

  • Basics: use . to access object keys or array indexes
    • name.last → "Anderson"
    • children.1 → "Alex"
  • Selector #: project or filter arrays
    • friends.#.age[44,68,47]
  • Filters inside #(...)
    • Contains: #(=c); Equals: #(==c); Not contains: #(!=c); Not equals: #(!==c)
    • Comparisons: age>47, age>=47, age<47, age<=47
    • Nested: friends.#(nets.#(=="fb"))
  • Escaping: keys containing . must escape the dot, e.g. fav\.movie or raw string literal fav\.movie

Modify & Delete

// Modify
tree.Find(`name.first`).SetString("Link")
tree.Find(`age`).SetInt(12)

// Remove object key
tree.Remove(`name.last`)

// Remove array element; clear array
tree.Remove(`children.0`)
tree.Remove(`children.#`)

Object Conversion & Std Encoding

// Any object → JSONTree
tree, err := qjson.ConvertToJSONTree(&struct{ X string `json:"x"` }{X:"1"})

// JSONTree ↔ std lib
var t qjson.JSONTree
json.Unmarshal([]byte(`{"a":1}`), &t)
data, _ := json.Marshal(&t)

Color Output

// Non‑indented color
fmt.Println(string(tree.ColorfulMarshal()))
// Indented color
fmt.Println(string(tree.ColorfulMarshalWithIndent()))

Equality, Hash & Diff

t1, _ := qjson.Decode([]byte(`{"a":1}`))
t2, _ := qjson.Decode([]byte(`{"a":1}`))
fmt.Println(t1.Equal(t2))      // true
fmt.Println(t1.Root.Hash())    // structural hash

// Diff
items := qjson.Diff(t1, t2)
fmt.Println(items.Exist())     // any differences
fmt.Println(items.String())    // human‑readable diff

Performance & Benchmarks

  • Object pools and compact data structures improve parsing and manipulation performance.
  • Run benchmarks:
go test -bench=. -benchmem

Testing & Coverage

  • Run:
go test ./... -cover
  • Coverage: use the printed result (e.g. 87%+) from your environment.
  • Optional: enable Codecov by adding CODECOV_TOKEN secret and check the badge on PRs.

Compatibility

  • Go 1.13 and above.
  • Standard library only, no external dependencies.

Notes

  • Path syntax includes escaping and filter expressions; validate complex paths in tests first.
  • unsafe conversions between string and []byte are used to reduce copies; ensure it fits your environment.
  • ANSI color output may not render in some terminals.

License

MIT — see LICENSE.

Documentation

Overview

Package qjson most of code here is copyed from std lib

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func JSONIndentMarshalWithPanic

func JSONIndentMarshalWithPanic(t interface{}) []byte

JSONIndentMarshalWithPanic json marshal with panic

func JSONMarshalWithPanic

func JSONMarshalWithPanic(t interface{}) []byte

JSONMarshalWithPanic json marshal with panic

func PrettyMarshal

func PrettyMarshal(v interface{}) []byte

PrettyMarshal marshal json with color

func PrettyMarshalWithIndent

func PrettyMarshalWithIndent(v interface{}) []byte

PrettyMarshalWithIndent marshal json with indent

Types

type Color

type Color byte

Color type

type DiffItem

type DiffItem struct {
	Type        DiffType
	Path        string
	Left, Right string
}

func (DiffItem) String

func (item DiffItem) String() string

type DiffItems

type DiffItems []DiffItem

func Diff

func Diff(t1, t2 *JSONTree) DiffItems

func (DiffItems) Exist

func (items DiffItems) Exist() bool

func (DiffItems) String

func (items DiffItems) String() string

type DiffType

type DiffType int
const (
	DiffOfType DiffType = iota
	DiffOfValue
)

func (DiffType) String

func (t DiffType) String() string

type Formatter

type Formatter struct {
	Indent int
}

Formatter json with indent

func NewFormatter

func NewFormatter() *Formatter

NewFormatter returns a new formatter with following default values.

func (*Formatter) Format

func (f *Formatter) Format(v *JSONTree) []byte

Format JSONTree

type JSONTree

type JSONTree struct {
	Root *Node
}

JSONTree represent full json

func ConvertToJSONTree

func ConvertToJSONTree(obj interface{}) (tree *JSONTree, err error)

ConvertToJSONTree any object to json tree

func Decode

func Decode(jsonBytes []byte) (*JSONTree, error)

Decode raw json bytes into JSONTree

func New

func New() *JSONTree

New json tree

func (*JSONTree) ColorfulMarshal

func (tree *JSONTree) ColorfulMarshal() []byte

ColorfulMarshal print json with color

func (*JSONTree) ColorfulMarshalWithIndent

func (tree *JSONTree) ColorfulMarshalWithIndent() []byte

ColorfulMarshalWithIndent print json with indent

func (*JSONTree) Equal

func (tree *JSONTree) Equal(t2 *JSONTree) bool

Equal two json tree

func (*JSONTree) Find

func (tree *JSONTree) Find(path string) *Node

Find json node/nodes by path selector

func (*JSONTree) IsNull

func (tree *JSONTree) IsNull() bool

IsNull tell node is null or not

func (*JSONTree) JSONIndentString

func (tree *JSONTree) JSONIndentString() string

JSONIndentString tree to string with indent

func (*JSONTree) JSONString

func (tree *JSONTree) JSONString() string

JSONString tree to string

func (*JSONTree) MarshalJSON

func (tree *JSONTree) MarshalJSON() ([]byte, error)

MarshalJSON json marshaller

func (*JSONTree) Release

func (tree *JSONTree) Release()

Release json tree for objects reuse

func (*JSONTree) Remove

func (tree *JSONTree) Remove(path string)

Remove json node

func (*JSONTree) UnmarshalJSON

func (tree *JSONTree) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON json unmarshaller

type Node

type Node struct {
	Type         NodeType
	Value        string
	ObjectValues []*ObjectElem
	ArrayValues  []*Node
	// contains filtered or unexported fields
}

Node represent json node

func CreateArrayNode

func CreateArrayNode() *Node

CreateArrayNode create array node

func CreateBoolNode

func CreateBoolNode() *Node

CreateBoolNode create bool node

func CreateFloatNode

func CreateFloatNode() *Node

CreateFloatNode create float node

func CreateIntegerNode

func CreateIntegerNode() *Node

CreateIntegerNode create integer node

func CreateNode

func CreateNode() *Node

CreateNode by pool

func CreateObjectNode

func CreateObjectNode() *Node

CreateObjectNode create object node

func CreateStringNode

func CreateStringNode() *Node

CreateStringNode create string node

func CreateStringNodeWithValue

func CreateStringNodeWithValue(val string) *Node

CreateStringNodeWithValue create string node

func (*Node) AddArrayElem

func (n *Node) AddArrayElem(elem *Node) *Node

AddArrayElem to node

func (*Node) AddObjectElem

func (n *Node) AddObjectElem(elem *ObjectElem) *Node

AddObjectElem to node

func (*Node) AsBool

func (n *Node) AsBool() bool

AsBool as boolean

func (*Node) AsFloat

func (n *Node) AsFloat() float64

AsFloat as float64

func (*Node) AsInt

func (n *Node) AsInt() int64

AsInt as integer

func (*Node) AsJSON

func (n *Node) AsJSON() string

AsJSON as json string

func (*Node) AsMap

func (n *Node) AsMap() map[string]*Node

AsMap create map for children

func (*Node) AsString

func (n *Node) AsString() string

AsString as string

func (*Node) AsTree

func (n *Node) AsTree() *JSONTree

AsTree create sub json tree

func (*Node) AsUint

func (n *Node) AsUint() uint64

AsUint as unsigned integer

func (*Node) Equal

func (n *Node) Equal(o *Node) bool

Equal two nodes

func (*Node) Find

func (n *Node) Find(key string) *Node

Find find offspring node by key

func (*Node) GetObjectElemByKey

func (n *Node) GetObjectElemByKey(key string) *ObjectElem

GetObjectElemByKey get object value by key

func (*Node) Hash

func (n *Node) Hash() uint64

func (*Node) IsBool

func (n *Node) IsBool() bool

IsBool tell node is boolean or not

func (*Node) IsFloat

func (n *Node) IsFloat() bool

IsFloat tell node is float or not

func (*Node) IsInteger

func (n *Node) IsInteger() bool

IsInteger tell node is num or not

func (*Node) IsNull

func (n *Node) IsNull() bool

IsNull tell node is null or not

func (*Node) IsNumber

func (n *Node) IsNumber() bool

IsNumber tell node is number or not

func (*Node) IsString

func (n *Node) IsString() bool

IsString tell node is string or not

func (*Node) MarshalJSON

func (n *Node) MarshalJSON() ([]byte, error)

MarshalJSON node is json marshaller too

func (*Node) Rehash

func (n *Node) Rehash() uint64

func (*Node) RemoveArrayElemByIndex

func (n *Node) RemoveArrayElemByIndex(idx int) bool

RemoveArrayElemByIndex remove array element

func (*Node) RemoveObjectElemByKey

func (n *Node) RemoveObjectElemByKey(key string) bool

RemoveObjectElemByKey remove object element

func (*Node) SetBool

func (n *Node) SetBool(b bool) *Node

SetBool to node

func (*Node) SetFloat

func (n *Node) SetFloat(f float64, prec int) *Node

SetFloat to node

func (*Node) SetInt

func (n *Node) SetInt(num int64) *Node

SetInt to node

func (*Node) SetObjectBoolElem

func (n *Node) SetObjectBoolElem(key string, value bool) *Node

SetObjectBoolElem set kv pair

func (*Node) SetObjectIntElem

func (n *Node) SetObjectIntElem(key string, value int64) *Node

SetObjectIntElem set kv pair

func (*Node) SetObjectNodeElem

func (n *Node) SetObjectNodeElem(key string, value *Node) *Node

SetObjectNodeElem set kv pair

func (*Node) SetObjectStringElem

func (n *Node) SetObjectStringElem(key, value string) *Node

SetObjectStringElem set kv pair

func (*Node) SetObjectUintElem

func (n *Node) SetObjectUintElem(key string, value uint64) *Node

SetObjectUintElem set kv pair

func (*Node) SetRawValue

func (n *Node) SetRawValue(str string) *Node

SetRawValue set raw json string to node

func (*Node) SetString

func (n *Node) SetString(str string) *Node

SetString to string node

func (*Node) SetUint

func (n *Node) SetUint(num uint64) *Node

SetUint to node

type NodeType

type NodeType byte

NodeType describe a json node type

const (
	// Null json node means null
	Null NodeType = iota
	// String json node means "any text"
	String
	// Bool json node means true/false
	Bool
	// Integer json node means integer
	Integer
	// Float json node means float number
	Float
	// Object json node means k-v object
	Object
	// Array json node means array json nodes
	Array
)

type ObjectElem

type ObjectElem struct {
	Key   *Node
	Value *Node
}

ObjectElem represent an object

func CreateObjectElem

func CreateObjectElem() *ObjectElem

CreateObjectElem by pool

func (*ObjectElem) MarshalJSON

func (e *ObjectElem) MarshalJSON() ([]byte, error)

MarshalJSON object node is json marshaller

Jump to

Keyboard shortcuts

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