jsonstream

package module
v0.0.0-...-e1a705a Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2025 License: BSD-2-Clause Imports: 10 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

jsonstream

A streaming-focused JSON decoder and filter for Go

Features

jsonstream aims to be a good solution for operating on large JSON datasets in a memory-efficient manner. Focus is on filtering/manipulating JSON in a streaming manner. It does not currently focus on decoding JSON data into golang native data types.

Is it faster than -insert otherpackage here-

No idea. It's faster than my previous attempt.

Standing on the shoulders of giants

This project is heavily influenced by Dave Cheney's pkg/json

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

View Source
const (
	RecursiveSearch    recursionType = true
	NonRecursiveSearch recursionType = false
)

Variables

View Source
var ErrExpectingComma = errors.New("stateObjectComma: expecting comma")
View Source
var ErrMissingKey = errors.New("stateObjectString: missing string key")
View Source
var ErrObjectNoColon = errors.New("stateObjectColon: expecting colon")
View Source
var ErrUnexpectedComma = errors.New("stateArrayValue: unexpected comma")
View Source
var ErrValueUnexpectedComma = errors.New("stateValue: unexpected comma")

Functions

func DropPropertyByMatchFunc

func DropPropertyByMatchFunc(drop func(JSONPath) JSONPath) func(TokenIterator) TokenIterator

func MatchFuncPropertyPartFunc

func MatchFuncPropertyPartFunc(matchFunc func([]byte) bool) func(p JSONPath) JSONPath

func MatchFuncPropertyPathEqual

func MatchFuncPropertyPathEqual(prefix JSONPath) func(p JSONPath) JSONPath

func MatchFuncPropertyPathPrefix

func MatchFuncPropertyPathPrefix(prefix JSONPath) func(p JSONPath) JSONPath

func NewCancellableFilter

func NewCancellableFilter(ctx context.Context) func(TokenIterator) TokenIterator

func NewJSONPathElem

func NewJSONPathElem(elem interface{}) interface{}

func NewJSONPathProp

func NewJSONPathProp(elem string) []byte

func NewTokenFromString

func NewTokenFromString(p string) []byte

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) Close

func (d *Decoder) Close() error

func (*Decoder) NextToken

func (d *Decoder) NextToken() (JSONPath, []byte, error)

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) Close

func (bm *Dropper) Close() error

func (*Dropper) GetReplaceIter

func (bm *Dropper) GetReplaceIter() TokenIterator

func (*Dropper) Save

func (bm *Dropper) Save(JSONPath, []byte, int)

func (*Dropper) Search

func (bm *Dropper) Search(p JSONPath, _ []byte) JSONPath

type Encoder

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

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

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

func (e *Encoder) EncodeOne(p JSONPath, tok []byte) error

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 Chain

func Chain(mws ...Filter) Filter

func DebugWrapper

func DebugWrapper(msg string) Filter

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 MatchPathPrefix(tokPath JSONPath, prefix JSONPath) JSONPath

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

func (s JSONPath) Clone() JSONPath

return a newly-allocated path struct that copies the underlying path strings to avoid buffer mutability problems

func (JSONPath) Len

func (s JSONPath) Len() int

func (JSONPath) PathArr

func (s JSONPath) PathArr(elemIdx int) (ret int, ok bool)

func (JSONPath) PathProp

func (s JSONPath) PathProp(elemIdx int) (ret []byte, ok bool)

func (JSONPath) PathPropFromEnd

func (s JSONPath) PathPropFromEnd(fromEnd int) (ret []byte, ok bool)

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

func (s JSONPath) PathPropOrIndexFromEnd(fromEnd int) (ret []byte, idx int, ok bool)

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)

func (JSONPath) String

func (s JSONPath) String() string

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

func (*PushableIterator) NextToken

func (mi *PushableIterator) NextToken() (JSONPath, []byte, error)

func (*PushableIterator) PushBack

func (mi *PushableIterator) PushBack(p JSONPath, t []byte, err 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

type TokenIterator interface {
	NextToken() (JSONPath, []byte, error)
	Close() error
}

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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