Documentation
¶
Overview ¶
Package jsonstream is a stream-oriented JSON processing library for processing, editing, and manipulating JSON
Copyright (c) 2021-2025 Dell Inc. or its subsidiaries. All rights reserved. Licensed to You under the Apache License, Version 2.0. See the LICENSE file for more details.
Copyright (c) 2021-2025 Dell Inc. or its subsidiaries. All rights reserved. Licensed to You under the Apache License, Version 2.0. See the LICENSE file for more details.
Copyright (c) 2021-2025 Dell Inc. or its subsidiaries. All rights reserved. Licensed to You under the Apache License, Version 2.0. See the LICENSE file for more details.
Copyright (c) 2021-2025 Dell Inc. or its subsidiaries. All rights reserved. Licensed to You under the Apache License, Version 2.0. See the LICENSE file for more details.
Index ¶
- Constants
- Variables
- func DropPropertyByMatchFunc(drop func(JSONPath) JSONPath) func(TokenIterator) TokenIterator
- func MatchFuncPropertyPartFunc(matchFunc func([]byte) bool) func(p JSONPath) JSONPath
- func MatchFuncPropertyPathEqual(prefix JSONPath) func(p JSONPath) JSONPath
- func MatchFuncPropertyPathPrefix(prefix JSONPath) func(p JSONPath) JSONPath
- func NewCancellableFilter(ctx context.Context) func(TokenIterator) TokenIterator
- func NewJSONPathElem(elem interface{}) interface{}
- func NewJSONPathProp(elem string) []byte
- func NewTokenFromString(p string) []byte
- func PrependPath(prependPath JSONPath) func(TokenIterator) TokenIterator
- type Decoder
- type Dropper
- type Encoder
- type Filter
- type JSONPath
- func (s JSONPath) Clone() JSONPath
- func (s JSONPath) Len() int
- func (s JSONPath) PathArr(elemIdx int) (ret int, ok bool)
- func (s JSONPath) PathProp(elemIdx int) (ret []byte, ok bool)
- func (s JSONPath) PathPropFromEnd(fromEnd int) (ret []byte, ok bool)
- func (s JSONPath) PathPropOrIndexFromEnd(fromEnd int) (ret []byte, idx int, ok bool)
- func (s JSONPath) String() string
- type PushableIterator
- type SearchReplacer
- type StringGenerator
- type TokenIterator
- type TokenIteratorStack
Constants ¶
const ( RecursiveSearch recursionType = true NonRecursiveSearch recursionType = false )
Variables ¶
var ErrExpectingComma = errors.New("stateObjectComma: expecting comma")
var ErrMissingKey = errors.New("stateObjectString: missing string key")
var ErrObjectNoColon = errors.New("stateObjectColon: expecting colon")
var ErrUnexpectedComma = errors.New("stateArrayValue: unexpected comma")
var ErrValueUnexpectedComma = errors.New("stateValue: unexpected comma")
Functions ¶
func DropPropertyByMatchFunc ¶
func DropPropertyByMatchFunc(drop func(JSONPath) JSONPath) func(TokenIterator) TokenIterator
func NewCancellableFilter ¶
func NewCancellableFilter(ctx context.Context) func(TokenIterator) TokenIterator
func NewJSONPathElem ¶
func NewJSONPathElem(elem interface{}) interface{}
func NewJSONPathProp ¶
func NewTokenFromString ¶
func PrependPath ¶
func PrependPath(prependPath JSONPath) func(TokenIterator) TokenIterator
Types ¶
type Decoder ¶
type Decoder struct {
// contains filtered or unexported fields
}
A Decoder decodes JSON values from an input stream.
func NewDecoder ¶
func NewDecoder(r io.ReadCloser) *Decoder
NewDecoder returns a new Decoder for the supplied Reader r.
func NewDecoderBuffer ¶
func NewDecoderBuffer(r io.ReadCloser, buf []byte) *Decoder
NewDecoderBuffer returns a new Decoder for the supplier Reader r, using the []byte buf provided for working storage.
func (*Decoder) NextToken ¶
NextToken breaks down the JSON stream into tuples that (hopefully?) efficiently represent the information in the JSON stream. The tuple is a (path, token) pair modelled (with a small exception) off the output from 'jq --stream'.
The []byte is valid until NextToken is called again. DO NOT RETAIN REFERENCES TO THE RETURNED JSONPath or []byte across calls to .NextToken()! Make a copy if you need to save them!
DIFFERENCES from encoding/json and pkg/json: NextToken does not return delimiters {, [, ], }, nor does it return commas or colons. The full JSON output can be reconstituted by using the path and token information.
NextToken guarantees that the incoming JSON is valid with properly nested delimiters. Any invalid JSON will return an error at the point of the invalidity.
Interpreting the path:
path is an []interface{} that contains either []byte that contain JSON
'property' strings, or int that contain the array index of JSON array
values.
from one call to NextToken to the next:
- only the last element can change from the previous call
- the path can shrink by exactly one element
- the path can grow arbitrarily: the last element of previous call can
change and an arbitrary number of elements may be added
When the path grows, that represents the beginning of an arbitrarily deep nesting of new objects.
When the token returned is a nil []byte, that is the end of the current path object/array.
An empty array is represented by a path that is longer than the previous path, with a nil token
An empty object is represented by a path that is longer than the previous path, with a nil token
type Dropper ¶
type Dropper struct {
// contains filtered or unexported fields
}
Dropper is a SearchReplacer that searches for things and doesnt replace them with anything
func (*Dropper) GetReplaceIter ¶
func (bm *Dropper) GetReplaceIter() TokenIterator
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
func NewEncoder ¶
func (*Encoder) Encode ¶
func (e *Encoder) Encode(ti TokenIterator) error
non-obvious: super important to check errors from Encode() and abort or you can leak Make sure you Close() the OUTPUT WRITER after Encode() is finished! The Encoder() implementation DOES NOT .Close() its output because it's a valid use case to encode multiple streams (serially) to the same output. certain cases, such as using an io.Pipe() as a writer will "leak" goroutines forever if you don't close the writer after you are finished.
func (*Encoder) EncodeOne ¶
EncodeOne will wrap a json token stream and write them to an io.WriteCloser path can be exactly the same as last (IFF token is nil, meaning end of object) path can grow longer arbitrarily, but is always torn down one at a time new path will always be exactly the same except the last component non-obvious: super important to check errors from EncodeOne() and abort or you can leak nolint: gocognit
type Filter ¶
type Filter func(TokenIterator) TokenIterator
func DebugWrapper ¶
func SearchReplace ¶
func SearchReplace(matcher SearchReplacer, recursive recursionType) Filter
SearchReplace returns a filter that can be applied to a decoder (ie. TokenIterator). This is the outer framework that you can plug in "SearchReplacer's" into. This outer object keeps track of state, when the underlying searchreplacer Search() method returns a non-nil JSONPath, this outer framework will start sending any tokens that match that path to the searchreplacer's Save() method. This ensures that any/all nested elements under the matching path are stripped from the incoming data stream. Once it hits the first 'non-matching' token, it then asks the searchreplacer to return a TokenIterator that should output whatever JSON should replace the original.
This filter operates recursively. Any output from the searchreplacer's TokenIterator is also sent through exactly the same filter stack. This means that each TokenIterator returned by GetReplaceIter() must be entirely self-contained and not rely on any global state. The recursion is handled by maintaining a "stack" of TokenIterators. We always return tokens from the topmost iterator in the stack. When that iterator returns EOF, it's popped off and we return tokens from the next one down. Each TokenIterator in the stack has a 'prepend path' that is prepended to all tokens it returns.
type JSONPath ¶
type JSONPath []interface{}
TODO: some ideas around adding methods to JSONPath for Equal(), HasPrefix() and then implement the matchfunc off that
func MatchPathPrefix ¶
func NewJSONPath ¶
func NewJSONPath(elems ...interface{}) JSONPath
construct a JSONPath 'by hand' and automatically quote strings []byte are assumed to be already quoted!
func (JSONPath) Clone ¶
return a newly-allocated path struct that copies the underlying path strings to avoid buffer mutability problems
func (JSONPath) PathPropFromEnd ¶
PathPropElemFromEnd will return the 'last - fromEnd' element requested, if the last path element is a json property string. return nil, false if the path element is an array or fromEnd is out of bounds. THE PROPERTY STRING RETURNED HAS THE QUOTES REMOVED (ease of use)
ex: fromEnd=0 == return final path element.
func (JSONPath) PathPropOrIndexFromEnd ¶
Check the element of a jsonpath at an index from the end of the path. Returns the byte array name of that element (if valid), the integer index of that element (if valid), and a boolean indicating whether anything was found. THE PROPERTY STRING RETURNED HAS THE QUOTES REMOVED (ease of use)
type PushableIterator ¶
type PushableIterator struct {
// contains filtered or unexported fields
}
func NewPushableIterator ¶
func NewPushableIterator(iter TokenIterator) *PushableIterator
func (*PushableIterator) Close ¶
func (mi *PushableIterator) Close() error
type SearchReplacer ¶
type SearchReplacer interface {
Search(JSONPath, []byte) JSONPath
Save(JSONPath, []byte, int)
GetReplaceIter() TokenIterator
Close() error
}
SearchReplacer interface is used to simplify doing search/replace operations on a JSON data stream. The low-level TokenIterator interface with the NextToken() method is the low-level general purpose API. The search replace class here sits on top of that and you can plug in SearchReplacer so the state machine Any object that implements this interface can be plugged in to filter (search/replace) JSON. much of the processing we do on our JSON can fit into something that looks roughly like this, but it's not appropriate for every use case.
type StringGenerator ¶
type StringGenerator struct {
// contains filtered or unexported fields
}
This reduces number of allocations for turning bytes into strings. It is faster than allocating strings individually...
func NewStringGenerator ¶
func NewStringGenerator(size uint) *StringGenerator
func (*StringGenerator) Generate ¶
func (s *StringGenerator) Generate(b []byte) string
type TokenIterator ¶
func DropDangling ¶
func DropDangling(iter TokenIterator) TokenIterator
func DropPropertyByPathMatch ¶
func DropPropertyByPathMatch(prefix JSONPath, iter TokenIterator) TokenIterator
func EmitOne ¶
func EmitOne(p JSONPath, tok []byte) TokenIterator
func SearchReplaceWithIterator ¶
func SearchReplaceWithIterator(matcher SearchReplacer, recursive recursionType, iter TokenIterator) TokenIterator
type TokenIteratorStack ¶
type TokenIteratorStack struct {
// contains filtered or unexported fields
}
func (*TokenIteratorStack) Append ¶
func (stack *TokenIteratorStack) Append(iter TokenIterator)
func (*TokenIteratorStack) Close ¶
func (stack *TokenIteratorStack) Close() (ret error)
func (*TokenIteratorStack) Len ¶
func (stack *TokenIteratorStack) Len() int
func (*TokenIteratorStack) NextToken ¶
func (stack *TokenIteratorStack) NextToken() (JSONPath, []byte, error)
func (*TokenIteratorStack) Top ¶
func (stack *TokenIteratorStack) Top() TokenIterator