qjson

package module
v0.0.0-...-1b4d3e0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2023 License: MIT Imports: 16 Imported by: 4

README

* qjson
simple and fast json encode/decode lib.

** unmarshal json bytes to JSONTree

#+begin_src
tree,err := Decode([]byte(`{"a":1}`))
// or
tree := JSONTree{}
err := json.Unmarshal([]byte(`{"a":1}`),&tree)
#+end_src

** marshal JSONTree to bytes

#+begin_src
data, err := json.Marshal(tree)
#+end_src

** query

A QJSON Path is a text string syntax that describes a search pattern for quickly retreiving values from a JSON payload.

*** Path structure

A QJSON Path is intended to be easily expressed as a series of components seperated by a `.` character.

**** Example

Given this JSON

#+begin_src
{
  "name": {"first": "Tom", "last": "Anderson"},
  "age":37,
  "children": ["Sara","Alex","Jack"],
  "fav.movie": "Deer Hunter",
  "friends": [
    {"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]},
    {"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]},
    {"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]}
  ]
}
#+end_src

The following QJSON Paths evaluate to the accompanying values.

**** Basic

In many cases you'll just want to retreive values by object name or array index.

#+begin_src go
name.last              "Anderson"      // tree.Find(`name.last`).AsString()
name.first             "Tom"           // tree.Find(`name.first`).AsString()
age                    37              // tree.Find(`age`).AsInt()
children               ["Sara","Alex","Jack"]          // tree.Find(`children`).AsJSON()
children.0             "Sara"      // tree.Find(`children.0`).AsString()
children.1             "Alex"      // tree.Find(`children.1`).AsString()
friends.1              {"first": "Roger", "last": "Craig", "age": 68}    // tree.Find(`friends.1`).AsJSON()
friends.1.first        "Roger"          // tree.Find(`friends.1.first`).AsString()
friends.#(nets.#(=="fb")).first     ["Dale","Roger","Jane"]  // == means equal
friends.#(nets.#(="f")).first    ["Dale","Roger"]  // = means contains
friends.#(last=Craig).first   ["Roger"]
friends.#(age>47).first     ["Roger"]
friends.#(age>=47).first     ["Roger","Jane"]
friends.#(age<47).first       ["Dale"]
friends.#(age<=47).first      ["Dale","Jane"]
// example json ["a","b","c"]
#(!=c)                       ["a","b"]   // not contains c
#(!==c)                       ["a","b"]  // not equal c
#+end_src

**** Escape character

Special purpose characters, such as ., can be escaped with \.

#+begin_src go
fav\.movie             "Deer Hunter"
#+end_src

You'll also need to make sure that the `\` character is correctly escaped when hardcoding a path in you source code.

#+begin_src go
// Go
tree.Find("fav\\.movie").AsString() // "Deer Hunter" must escape the slash
tree.Find(`fav\.movie`).AsString()  // "Deer Hunter" no need to escape the slash
#+end_src

** modify

#+begin_src go
// rename Tom to Link
tree.Find(`name.first`).SetString("Link")
// change age to 12
tree.Find(`age`).SetInt(12)
#+end_src

** benchmark

#+begin_src 
goos: darwin
goarch: amd64
pkg: github.com/qjpcpu/qjson
cpu: Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz
BenchmarkMarshalQJSON-12          735711              1631 ns/op            1024 B/op          1 allocs/op
BenchmarkUnmarshalQJSON-12         94591             12673 ns/op            1039 B/op         58 allocs/op
BenchmarkMarshalStd-12             50536             23592 ns/op            9979 B/op        215 allocs/op
BenchmarkUnmarshalStd-12           54302             21827 ns/op            9152 B/op        195 allocs/op
PASS
ok      github.com/qjpcpu/qjson 8.084s
#+end_src

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