File: README.md

package info (click to toggle)
golang-github-tdewolff-parse 2.8.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 888 kB
  • sloc: makefile: 2
file content (81 lines) | stat: -rw-r--r-- 1,809 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# JSON [![API reference](https://img.shields.io/badge/godoc-reference-5272B4)](https://pkg.go.dev/github.com/tdewolff/parse/v2/json?tab=doc)

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.

## Installation
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"

## Parser
### Usage
The following initializes a new Parser with io.Reader `r`:
``` go
p := json.NewParser(parse.NewInput(r))
```

To tokenize until EOF an error, use:
``` go
for {
	gt, text := p.Next()
	switch gt {
	case json.ErrorGrammar:
		// error or EOF set in p.Err()
		return
	// ...
	}
}
```

All grammars:
``` go
ErrorGrammar       GrammarType = iota // extra grammar when errors occur
WhitespaceGrammar                     // space \t \r \n
LiteralGrammar                        // null true false
NumberGrammar
StringGrammar
StartObjectGrammar // {
EndObjectGrammar   // }
StartArrayGrammar  // [
EndArrayGrammar    // ]
```

### Examples
``` go
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))
		// ...
		}
	}
}
```

## License
Released under the [MIT license](https://github.com/tdewolff/parse/blob/master/LICENSE.md).

[1]: http://golang.org/ "Go Language"