package json

import "github.com/tdewolff/parse/v2/json"

Package json is a JSON parser following the specifications at http://json.org/.

Index

Examples

Types

type GrammarType

type GrammarType uint32

GrammarType determines the type of grammar

const (
	ErrorGrammar GrammarType = iota // extra grammar when errors occur
	WhitespaceGrammar
	LiteralGrammar
	NumberGrammar
	StringGrammar
	StartObjectGrammar // {
	EndObjectGrammar   // }
	StartArrayGrammar  // [
	EndArrayGrammar    // ]
)

GrammarType values.

func (GrammarType) String

func (gt GrammarType) String() string

String returns the string representation of a GrammarType.

type Parser

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

Parser is the state for the lexer.

func NewParser

func NewParser(r *parse.Input) *Parser

NewParser returns a new Parser for a given io.Reader.

Example

Code:

{
	p := NewParser(parse.NewInputString(`{"key": 5}`))
	out := ""
	for {
		state := p.State()
		gt, data := p.Next()
		if gt == ErrorGrammar {
			break
		}
		out += string(data)
		if state == ObjectKeyState && gt != EndObjectGrammar {
			out += ":"
		}
		// not handling comma insertion
	}
	fmt.Println(out)
	// Output: {"key":5}
}

Output:

{"key":5}

func (*Parser) Err

func (p *Parser) Err() error

Err returns the error encountered during tokenization, this is often io.EOF but also other errors can be returned.

func (*Parser) Next

func (p *Parser) Next() (GrammarType, []byte)

Next returns the next Grammar. It returns ErrorGrammar when an error was encountered. Using Err() one can retrieve the error message.

func (*Parser) State

func (p *Parser) State() State

State returns the state the parser is currently in (ie. which token is expected).

type State

type State uint32

State determines the current state the parser is in.

const (
	ValueState State = iota // extra token when errors occur
	ObjectKeyState
	ObjectValueState
	ArrayState
)

State values.

func (State) String

func (state State) String() string

String returns the string representation of a State.

Source Files

parse.go

Version
v2.7.20 (latest)
Published
Jan 28, 2025
Platform
linux/amd64
Imports
2 packages
Last checked
1 day ago

Tools for package owners.