jsonparser_airp

package module
v0.9.13 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2018 License: BSD-3-Clause Imports: 12 Imported by: 0

README

jsonparser_airp

See doc.go and use go doc github.com/D1CED/jsonparser_airp. For usage look into 'example_test.go'.

go get github.com/D1CED/jsonparser_airp

This package is inspired by: Lexical Scanning in Go - Rob Pike

Documentation

Overview

Package jsonparser_airp encodes and decodes JSON.

In contrast to encoding/json airp is centered around an AST (Abstract Syntax Tree) model. An AST can be manipulated and new nodes can be created. Every non error-node is valid JSON.

airp is partly comartible with encoding/json. Node fulfills the json.Marshaler/Unmarshaler interfaces.

Some differences between this package and encoding/json:

  • Empty arrays or objects will be represented by their empty types ([]/{}) instead of null
  • bytes slices will be interpreded as strings instead of as base64 encoded data

TODO(JMH): better handle escape sequences TODO(JMH): reimplement lexer and parser

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrNotArrayOrObject = errors.New("not array or object")

ErrNotArrayOrObject is a common error that multiple methods of Node or KeyNode return. This signals that the Node type is a standalone value.

Functions

func EqNode

func EqNode(a, b *Node) bool

EqNode compares the nodes and all their children. Object keys order is abitary.

func Marshal

func Marshal(v interface{}) ([]byte, error)

func Unmarshal

func Unmarshal(data []byte, v interface{}) (err error)

Types

type JSONType

type JSONType uint8

JSONType is an enum for any JSON-types

const (
	Error JSONType = iota
	Null
	Bool
	Number
	String
	Array
	Object
)

JSONTypes to caompare nodes of an ast with. The zero value signals invalid.

func (JSONType) String

func (i JSONType) String() string

type KeyNode added in v0.9.11

type KeyNode struct {
	Key string
	*Node
}

func StandaloneNode

func StandaloneNode(key, str string) KeyNode

StandaloneNode generates a single json value of str. It panics if str is a compund json expression.

type Node

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

Node is one node of a tree building a JSON-AST. Depending on its internal type it holds a different value:

JSONType ValueType
Error    nil
Null     nil
Bool     bool
Number   float64
String   string
Array    []*Node
Object   []KeyNode

func NewJSON

func NewJSON(b []byte) (*Node, error)

NewJSON reads from b and generates an AST

func NewJSONGo

func NewJSONGo(val interface{}) (*Node, error)

NewJSONGo reads in a Go-value and generates a json ast that can be manipulated easily.

func NewJSONReader added in v0.9.13

func NewJSONReader(r io.Reader) (*Node, error)

NewJSONReader reads from r and generates an AST

func NewJSONString added in v0.9.13

func NewJSONString(s string) (*Node, error)

NewJSONString reads from s and generates an AST

func (*Node) AddChildren

func (n *Node) AddChildren(nn ...KeyNode)

AddChildren appends nn nodes to the Array or Object n. It panics if n is not of the two mentioned types or if appended values in an object don't have keys.

func (*Node) Copy added in v0.9.13

func (n *Node) Copy() *Node

Copy creates a deep copy of a Node.

func (*Node) GetChild

func (n *Node) GetChild(name string) (*Node, bool)

GetChild returns the node specifiend by name. The key "" always returns the node itself.

func (*Node) GetChildrenKeys

func (n *Node) GetChildrenKeys() []string

GetChildrenKeys returns a slice of all keys an Object or array holds. It is nil if n is not array or object and is not nil but is non-nil with a lengh of 0 if n is an empty array or object.

func (*Node) JSON2Go

func (n *Node) JSON2Go(val interface{}) (err error)

JSON2Go reads contents from n and writes them into val. val has to be a pointer value and may panic if types don't match.

func (*Node) Key

func (n *Node) Key() string

Key returns the name of a Node.

func (*Node) Len

func (n *Node) Len() int

Len gives the length of an array or items in an object

func (*Node) MarshalJSON

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

MarshalJSON implements the json.Mashaler interface for Node

Example
package main

import (
	"fmt"

	airp "github.com/d1ced/jsonparser_airp"
)

func main() {
	n := airp.StandaloneNode("", "{}")
	m := airp.StandaloneNode("Num", "3.125")
	o := airp.StandaloneNode("Str", `"Hello, World!"`)
	n.AddChildren(m, o)
	data, _ := n.MarshalJSON()
	fmt.Printf("%s", data)
}
Output:

{"Num": 3.125, "Str": "Hello, World!"}

func (*Node) RemoveChild

func (n *Node) RemoveChild(key string) error

RemoveChild removes key from the ast corrctly reducing arrays

func (*Node) SetChild

func (n *Node) SetChild(kn KeyNode) error

SetChild adds or replaces the child key of n with val. SetChild does not add multiple level of objects. SetChild panics a to extended object is not array or object.

func (*Node) String

func (n *Node) String() string

String formats an ast as valid JSON with no whitspace.

func (*Node) Total

func (n *Node) Total() int

Total returns the number of total nodes hold by n

func (*Node) Type

func (n *Node) Type() JSONType

Type returns the JSONType of a node.

func (*Node) UnmarshalJSON

func (n *Node) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmashaler interface for Node

Example
package main

import (
	"fmt"

	airp "github.com/d1ced/jsonparser_airp"
)

func main() {
	data := []byte(`{"a": 20, "b": [true, null]}`)
	root := airp.Node{}
	_ = root.UnmarshalJSON(data)
	// root now holds the top of the JSON ast.
	fmt.Println(root.String())
}
Output:

{"a":20,"b":[true,null]}

func (*Node) Value

func (n *Node) Value() (interface{}, error)

Value creates the Go representation of a JSON-Node. Like encoding/json the possible underlying types of the first return parameter are:

Object    map[string]interface{}
Array     []interface{}
String    string
Number    float64
Bool      bool
Null      nil (with the error being nil too)
Example
package main

import (
	"fmt"

	airp "github.com/d1ced/jsonparser_airp"
)

func main() {
	data := []byte(`[{"a": null}, true]`)
	root := airp.Node{}
	_ = root.UnmarshalJSON(data)
	v, _ := root.Value()
	fmt.Println(v)
}
Output:

[map[a:<nil>] true]

func (*Node) WriteIndent

func (n *Node) WriteIndent(w io.Writer, indent string) (int, error)

WriteIndent writes the AST hold by n to w with the given indent (preferably spaces or a tab).

func (*Node) WriteJSON

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

WriteJSON writes the AST hold by n to w with the same representation as n.String() and no whitspace.

type ParseError

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

ParseError captures information on errors when parsing.

func (*ParseError) Error

func (e *ParseError) Error() string

func (*ParseError) Where

func (e *ParseError) Where() (row, col int)

Where returns the row and column where the syntax error in json occured.

Jump to

Keyboard shortcuts

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