| 1 | """Based on https://github.com/pyparsing/pyparsing/blob/master/examples/jsonParser.py. |
| 2 | |
| 3 | """ |
| 4 | |
| 5 | import timeit |
| 6 | |
| 7 | import pyparsing |
| 8 | from pyparsing import Keyword |
| 9 | from pyparsing import Suppress |
| 10 | from pyparsing import dblQuotedString |
| 11 | from pyparsing import Forward |
| 12 | from pyparsing import Group |
| 13 | from pyparsing import delimitedList |
| 14 | from pyparsing import Optional |
| 15 | from pyparsing import pyparsing_common |
| 16 | from pyparsing import Dict |
| 17 | |
| 18 | |
| 19 | def create_grammar(): |
| 20 | TRUE = Keyword('true') |
| 21 | FALSE = Keyword('false') |
| 22 | NULL = Keyword('null') |
| 23 | |
| 24 | LBRACK, RBRACK, LBRACE, RBRACE, COLON = map(Suppress, '[]{}:') |
| 25 | |
| 26 | string = dblQuotedString() |
| 27 | number = pyparsing_common.number() |
| 28 | |
| 29 | object_ = Forward() |
| 30 | value = Forward() |
| 31 | elements = delimitedList(value) |
| 32 | array = Group(LBRACK + Optional(elements, []) + RBRACK) |
| 33 | value <<= (string |
| 34 | | number |
| 35 | | Group(object_) |
| 36 | | array |
| 37 | | TRUE |
| 38 | | FALSE |
| 39 | | NULL) |
| 40 | member = Group(string + COLON + value) |
| 41 | members = delimitedList(member) |
| 42 | object_ <<= Dict(LBRACE + Optional(members) + RBRACE) |
| 43 | |
| 44 | return value |
| 45 | |
| 46 | |
| 47 | def parse_time(json_string, iterations=1): |
| 48 | grammar = create_grammar() |
| 49 | |
| 50 | def _parse(): |
| 51 | grammar.parseString(json_string) |
| 52 | |
| 53 | return timeit.timeit(_parse, number=iterations) |
| 54 | |
| 55 | |
| 56 | def parse(json_string): |
| 57 | grammar = create_grammar() |
| 58 | |
| 59 | return grammar.parseString(json_string).asList() |
| 60 | |
| 61 | |
| 62 | def version(): |
| 63 | return pyparsing.__version__ |