| 1 |
# JSON [](https://pkg.go.dev/github.com/tdewolff/parse/v2/json?tab=doc) |
| 2 |
|
| 3 |
This package is a JSON lexer (ECMA-404) written in [Go][1]. It follows the specification at [JSON](http://json.org/). The lexer takes an io.Reader and converts it into tokens until the EOF. |
| 4 |
|
| 5 |
## Installation |
| 6 |
Run the following command |
| 7 |
|
| 8 |
go get -u github.com/tdewolff/parse/v2/json |
| 9 |
|
| 10 |
or add the following import and run project with `go get` |
| 11 |
|
| 12 |
import "github.com/tdewolff/parse/v2/json" |
| 13 |
|
| 14 |
## Parser |
| 15 |
### Usage |
| 16 |
The following initializes a new Parser with io.Reader `r`: |
| 17 |
``` go |
| 18 |
p := json.NewParser(parse.NewInput(r)) |
| 19 |
``` |
| 20 |
|
| 21 |
To tokenize until EOF an error, use: |
| 22 |
``` go |
| 23 |
for { |
| 24 |
gt, text := p.Next() |
| 25 |
switch gt { |
| 26 |
case json.ErrorGrammar: |
| 27 |
// error or EOF set in p.Err() |
| 28 |
return |
| 29 |
// ... |
| 30 |
} |
| 31 |
} |
| 32 |
``` |
| 33 |
|
| 34 |
All grammars: |
| 35 |
``` go |
| 36 |
ErrorGrammar GrammarType = iota // extra grammar when errors occur |
| 37 |
WhitespaceGrammar // space \t \r \n |
| 38 |
LiteralGrammar // null true false |
| 39 |
NumberGrammar |
| 40 |
StringGrammar |
| 41 |
StartObjectGrammar // { |
| 42 |
EndObjectGrammar // } |
| 43 |
StartArrayGrammar // [ |
| 44 |
EndArrayGrammar // ] |
| 45 |
``` |
| 46 |
|
| 47 |
### Examples |
| 48 |
``` go |
| 49 |
package main |
| 50 |
|
| 51 |
import ( |
| 52 |
"os" |
| 53 |
|
| 54 |
"github.com/tdewolff/parse/v2/json" |
| 55 |
) |
| 56 |
|
| 57 |
// Tokenize JSON from stdin. |
| 58 |
func main() { |
| 59 |
p := json.NewParser(parse.NewInput(os.Stdin)) |
| 60 |
for { |
| 61 |
gt, text := p.Next() |
| 62 |
switch gt { |
| 63 |
case json.ErrorGrammar: |
| 64 |
if p.Err() != io.EOF { |
| 65 |
fmt.Println("Error on line", p.Line(), ":", p.Err()) |
| 66 |
} |
| 67 |
return |
| 68 |
case json.LiteralGrammar: |
| 69 |
fmt.Println("Literal", string(text)) |
| 70 |
case json.NumberGrammar: |
| 71 |
fmt.Println("Number", string(text)) |
| 72 |
// ... |
| 73 |
} |
| 74 |
} |
| 75 |
} |
| 76 |
``` |
| 77 |
|
| 78 |
## License |
| 79 |
Released under the [MIT license](https://github.com/tdewolff/parse/blob/master/LICENSE.md). |
| 80 |
|
| 81 |
[1]: http://golang.org/ "Go Language" |