njson

package module
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2019 License: Apache-2.0 Imports: 11 Imported by: 0

README

Build Status GoDoc Go Report codecov

njson

High performance parsing and manipulation of JSON documents for Go.

Inspired by github.com/valyala/fastjson

Features

  • Does not try to be a 'drop-in' replacement for encoding/json
  • Deserialize arbitrary JSON input to a DOM tree
  • Manipulate DOM tree
  • Path lookups
  • Lazy unescape and number conversions for faster parsing
  • Reserialze to JSON data
  • Iterate over tree
  • Documents can be reused to avoid allocations
  • Fast, fast, fast
  • [WIP] Support for reflect based struct Marshal/Unmarshal via github.com/alxarch/njson/unjson package
  • [WIP] CLI tool for Marshal/Unmarshal generated code via github.com/alxarch/njson/cmd/njson package

Usage


	d := njson.Document{}

	root, _, _ := d.Parse(`{"answer":42, "foo": {"bar": "baz"}}`)

	answer, _ := root.Get("answer").ToInt()
	fmt.Println(answer)

	n := root.Lookup("foo", "bar")
	bar := n.Unescaped()
	fmt.Println(bar)

	n.SetString("Hello, 世界")

	data := make([]byte, 64)
	data, _ = root.AppendJSON(data[:0])
	fmt.Println(string(data))

	// Output:
	// 42
	// baz
	// {"answer":42,"foo":{"bar":"Hello, 世界"}}

Documentation

Overview

Example
package main

import (
	"fmt"

	"github.com/alxarch/njson"
)

func main() {
	d := njson.Document{}

	root, _, _ := d.Parse(`{"answer":42, "foo": {"bar": "baz"}}`)

	answer, _ := root.Get("answer").ToInt()
	fmt.Println(answer)

	n := root.Lookup("foo", "bar")
	bar := n.Unescaped()
	fmt.Println(bar)

	n.SetString("Hello, 世界")

	data := make([]byte, 64)
	data, _ = root.AppendJSON(data[:0])
	fmt.Println(string(data))

}
Output:

42
baz
{"answer":42,"foo":{"bar":"Hello, 世界"}}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func PrintJSON

func PrintJSON(w io.Writer, a Appender) (n int, err error)

PrintJSON is a helper to write an Appender to an io.Writer

Types

type Appender

type Appender interface {
	AppendJSON([]byte) ([]byte, error)
}

Appender is a Marshaler interface for buffer append workflows.

type Document

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

Document is a JSON document.

func Blank

func Blank() *Document

Blank returns a blank document from the default pool. Use Document.Close() to reset and return the document to the pool.

func (*Document) AppendJSON

func (d *Document) AppendJSON(dst []byte) ([]byte, error)

AppendJSON appends the JSON data of the document root node to a byte slice.

func (*Document) Array

func (d *Document) Array() Node

Array adds a new empty Array node to the document.

func (*Document) Close

func (d *Document) Close()

Close resets and returns the document to the default pool to be reused.

func (*Document) False

func (d *Document) False() Node

False adds a new Boolean node with it's value set to false to the document.

func (*Document) Node added in v0.0.5

func (d *Document) Node(id uint) Node

Node returns a node with id set to id.

func (*Document) Null

func (d *Document) Null() Node

Null adds a new Null node to the document.

func (*Document) Number

func (d *Document) Number(f float64) Node

Number adds a new Number node to the document.

func (*Document) Object

func (d *Document) Object() Node

Object adds a new empty Object node to the document.

func (*Document) Parse

func (d *Document) Parse(s string) (Node, string, error)

Parse parses a JSON string and returns the root node

func (*Document) Reset

func (d *Document) Reset()

Reset resets the document to empty.

func (*Document) Root added in v0.0.5

func (d *Document) Root() Node

Root returns the document root node.

func (*Document) Text

func (d *Document) Text(s string) Node

Text adds a new String node to the document escaping JSON unsafe characters.

func (*Document) TextHTML

func (d *Document) TextHTML(s string) Node

TextHTML adds a new String node to the document escaping HTML and JSON unsafe characters.

func (*Document) TextRaw

func (d *Document) TextRaw(s string) Node

TextRaw adds a new String node to the document.

func (*Document) True

func (d *Document) True() Node

True adds a new Boolean node with it's value set to true to the document.

type IterV

type IterV struct {
	V
	// contains filtered or unexported fields
}

IterV is an iterator over a node's values.

func (*IterV) Close

func (i *IterV) Close()

Close closes the iterator unlinking the values slice.

func (*IterV) Index

func (i *IterV) Index() int

Index returns the current iteration index. Before Next() is called for the first time it returns -1. After the iteration has finished it returns -2.

func (*IterV) Len

func (i *IterV) Len() int

Len returns the length of the values.

func (*IterV) Next

func (i *IterV) Next() bool

Next increments the iteration cursor and checks if the iterarion finished.

func (*IterV) Reset

func (i *IterV) Reset()

Reset resets the iterator.

func (*IterV) Value added in v0.0.12

func (i *IterV) Value() Node

Value returns the node of the current iteration value.

type Node

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

Node is a reference to a node in a JSON Document. It is a versioned reference to avoid document manipulation after reset.

func (Node) Append

func (n Node) Append(values ...Node)

Append appends a node id to an Array node's values.

func (Node) AppendJSON

func (n Node) AppendJSON(dst []byte) ([]byte, error)

AppendJSON appends a node's JSON data to a byte slice.

func (Node) Data added in v0.0.11

func (n Node) Data() (string, Type)

Data returns a node's raw string and type

func (Node) Del

func (n Node) Del(key string)

Del finds a key in an Object node's values and removes it. It does not keep the order of keys.

func (Node) Document

func (n Node) Document() *Document

Document returns a node's document.

func (Node) Get

func (n Node) Get(key string) Node

Get gets a Node by key. If the key is not found the returned node's id will be MaxID and the Node will behave as empty.

func (Node) ID

func (n Node) ID() uint

ID returns a node's id.

func (Node) Index

func (n Node) Index(i int) Node

Index gets the Node at offset i of an Array. If the index is out of bounds it sets the id to MaxUint and the Node will behave as empty but still have a usable reference to Document.

func (Node) Lookup

func (n Node) Lookup(path ...string) Node

Lookup finds a node by path

func (Node) PrintJSON

func (n Node) PrintJSON(w io.Writer) (int, error)

PrintJSON writes JSON to an io.Writer.

func (Node) Raw

func (n Node) Raw() string

Raw returns the JSON string of a Node's value. Object and Array nodes return an empty string.

func (Node) Remove

func (n Node) Remove(i int)

Remove removes the value at offset i of an Array node.

func (Node) Replace

func (n Node) Replace(i int, value Node)

Replace replaces the value at offset i of an Array node.

func (Node) Set

func (n Node) Set(key string, value Node)

Set assigns a Node to the key of an Object Node. Since most keys need no escaping it doesn't escape the key. If the key needs escaping use strjson.Escaped.

func (Node) SetFalse

func (n Node) SetFalse()

SetFalse sets a Node's value to false.

func (Node) SetFloat

func (n Node) SetFloat(f float64)

SetFloat sets a Node's value to a float number.

func (Node) SetInt

func (n Node) SetInt(i int64)

SetInt sets a Node's value to an integer.

func (Node) SetNull

func (n Node) SetNull()

SetNull sets a Node's value to null.

func (Node) SetString

func (n Node) SetString(s string)

SetString sets a Node's value to a string escaping invalid JSON characters.

func (Node) SetStringHTML

func (n Node) SetStringHTML(s string)

SetStringHTML sets a Node's value to a string escaping invalid JSON and unsafe HTML characters.

func (Node) SetStringRaw

func (n Node) SetStringRaw(s string)

SetStringRaw sets a Node's value to a string without escaping. Unless the provided string is guaranteed to not contain any JSON invalid characters, JSON output from this Node will be invalid.

func (Node) SetTrue

func (n Node) SetTrue()

SetTrue sets a Node's value to true.

func (Node) SetUint

func (n Node) SetUint(u uint64)

SetUint sets a Node's value to an unsigned integer.

func (Node) Slice

func (n Node) Slice(i, j int)

Slice reslices an Array node.

func (Node) Strip added in v0.0.4

func (n Node) Strip(key string)

Strip recursively deletes a key from a node.

func (Node) ToBool

func (n Node) ToBool() (bool, bool)

ToBool converts a Node to bool.

func (Node) ToFloat

func (n Node) ToFloat() (float64, bool)

ToFloat converts a node's value to float64.

func (Node) ToInt

func (n Node) ToInt() (int64, bool)

ToInt converts a node's value to int64.

func (Node) ToInterface

func (n Node) ToInterface() (interface{}, bool)

ToInterface converts a Node to a generic interface{}.

func (Node) ToUint

func (n Node) ToUint() (uint64, bool)

ToUint converts a node's value to uint64.

func (Node) Type

func (n Node) Type() Type

Type returnsa a Node's type.

func (Node) TypeError

func (n Node) TypeError(want Type) error

TypeError returns an error for a type not matching a Node's type.

func (Node) Unescaped

func (n Node) Unescaped() string

Unescaped unescapes the value of a String Node.

func (Node) Values

func (n Node) Values() IterV

Values returns a value iterator over an Array or Object values.

func (Node) With

func (n Node) With(id uint) Node

With returns a document node for id.

func (Node) WrapUnmarshalJSON

func (n Node) WrapUnmarshalJSON(u json.Unmarshaler) (err error)

WrapUnmarshalJSON wraps a call to the json.Unmarshaler interface

func (Node) WrapUnmarshalText

func (n Node) WrapUnmarshalText(u encoding.TextUnmarshaler) (err error)

WrapUnmarshalText wraps a call to the encoding.TextUnmarshaler interface

type ParseError added in v0.0.9

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

ParseError signifies an invalid token in JSON data

func (*ParseError) Error added in v0.0.9

func (e *ParseError) Error() string

func (*ParseError) Pos added in v0.0.9

func (e *ParseError) Pos() int

Pos returns the offset at which the error ocurred

func (*ParseError) Type added in v0.0.9

func (e *ParseError) Type() Type

Type returns type of value that was being parsed when the error ocurred.

type Pool added in v0.0.5

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

Pool is a pool of document objects

func (*Pool) Get added in v0.0.5

func (pool *Pool) Get() *Document

Get returns a blank document from the pool

func (*Pool) Put added in v0.0.5

func (pool *Pool) Put(d *Document)

Put returns a document to the pool

type Type

type Type uint8

Type is the type of a node.

const (
	TypeInvalid Type = iota
	TypeString  Type = 1 << iota
	TypeObject
	TypeArray
	TypeNumber
	TypeBoolean
	TypeNull
	TypeAnyValue = TypeString | TypeNumber | TypeBoolean | TypeObject | TypeArray | TypeNull
)

Token types and type masks

func (Type) IsValue

func (t Type) IsValue() bool

IsValue checks if t matches TypeAnyValue

func (Type) String

func (t Type) String() string

func (Type) Types

func (t Type) Types() (types []Type)

Types returns all types of a typemask

type UnexpectedEOF added in v0.0.9

type UnexpectedEOF Type

UnexpectedEOF signifies incomplete JSON data

func (UnexpectedEOF) Error added in v0.0.9

func (e UnexpectedEOF) Error() string

type Unmarshaler

type Unmarshaler interface {
	UnmarshalNodeJSON(n Node) error
}

Unmarshaler is the interface implemented by types that can unmarshal from a Node.

type V

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

V is a node's value referencing it's id. Array node's values have empty string keys.

func (*V) ID

func (v *V) ID() uint

ID returns a value's id

func (*V) Key

func (v *V) Key() string

Key returns a value's key

Directories

Path Synopsis
cmd
internal
Package unjson uses reflection to marshal/unmarshal JSON from `njson.Node` input It is combatible with the default `encoding/json` package but the API is different so it's *not* a 'drop-in' replacement.
Package unjson uses reflection to marshal/unmarshal JSON from `njson.Node` input It is combatible with the default `encoding/json` package but the API is different so it's *not* a 'drop-in' replacement.

Jump to

Keyboard shortcuts

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