|
1 anno fa | |
---|---|---|
.. | ||
README.md | 1 anno fa | |
parse.go | 1 anno fa |
This package is a JSON lexer (ECMA-404) written in Go. It follows the specification at JSON. The lexer takes an io.Reader and converts it into tokens until the EOF.
Run the following command
go get -u github.com/tdewolff/parse/v2/json
or add the following import and run project with go get
import "github.com/tdewolff/parse/v2/json"
The following initializes a new Parser with io.Reader r
:
p := json.NewParser(parse.NewInput(r))
To tokenize until EOF an error, use:
for {
gt, text := p.Next()
switch gt {
case json.ErrorGrammar:
// error or EOF set in p.Err()
return
// ...
}
}
All grammars:
ErrorGrammar GrammarType = iota // extra grammar when errors occur
WhitespaceGrammar // space \t \r \n
LiteralGrammar // null true false
NumberGrammar
StringGrammar
StartObjectGrammar // {
EndObjectGrammar // }
StartArrayGrammar // [
EndArrayGrammar // ]
package main
import (
"os"
"github.com/tdewolff/parse/v2/json"
)
// Tokenize JSON from stdin.
func main() {
p := json.NewParser(parse.NewInput(os.Stdin))
for {
gt, text := p.Next()
switch gt {
case json.ErrorGrammar:
if p.Err() != io.EOF {
fmt.Println("Error on line", p.Line(), ":", p.Err())
}
return
case json.LiteralGrammar:
fmt.Println("Literal", string(text))
case json.NumberGrammar:
fmt.Println("Number", string(text))
// ...
}
}
}
Released under the MIT license.