| 1 |
"""Based on |
| 2 |
https://github.com/transceptor-technology/pyleri/blob/master/examples/json_grammar.py. |
| 3 |
|
| 4 |
""" |
| 5 |
|
| 6 |
import timeit |
| 7 |
|
| 8 |
import pyleri |
| 9 |
from pyleri import Ref |
| 10 |
from pyleri import Choice |
| 11 |
from pyleri import Grammar |
| 12 |
from pyleri import Regex |
| 13 |
from pyleri import Keyword |
| 14 |
from pyleri import Sequence |
| 15 |
from pyleri import List |
| 16 |
|
| 17 |
|
| 18 |
class JsonGrammar(Grammar): |
| 19 |
START = Ref() |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
r_string = Regex('(")(?:(?=(\\\?))\\2.)*?\\1') |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
r_float = Regex('-?[0-9]+\.?[0-9]+') |
| 29 |
r_integer = Regex('-?[0-9]+') |
| 30 |
|
| 31 |
k_true = Keyword('true') |
| 32 |
k_false = Keyword('false') |
| 33 |
k_null = Keyword('null') |
| 34 |
|
| 35 |
json_map_item = Sequence(r_string, ':', START) |
| 36 |
|
| 37 |
json_map = Sequence('{', List(json_map_item), '}') |
| 38 |
json_array = Sequence('[', List(START), ']') |
| 39 |
|
| 40 |
START = Choice(r_string, |
| 41 |
r_float, |
| 42 |
r_integer, |
| 43 |
k_true, |
| 44 |
k_false, |
| 45 |
k_null, |
| 46 |
json_map, |
| 47 |
json_array) |
| 48 |
|
| 49 |
|
| 50 |
def parse_time(json_string, iterations): |
| 51 |
grammar = JsonGrammar() |
| 52 |
|
| 53 |
def _parse(): |
| 54 |
grammar.parse(json_string) |
| 55 |
|
| 56 |
return timeit.timeit(_parse, number=iterations) |
| 57 |
|
| 58 |
|
| 59 |
def parse(json_string): |
| 60 |
return JsonGrammar().parse(json_string) |
| 61 |
|
| 62 |
|
| 63 |
def version(): |
| 64 |
return pyleri.__version__ |