Source

ppparse / demo / demo_json.py


from ppparse import make_scan, make_parse

LEX = r"""
$int        : [-]? ( [0] | [1-9] [0-9]* )
$frac       : [.] [0-9]+
$exp        : [eE] [+-] [0-9]+

$char       : [^\0-\x1F"\\]
$escape     : [\\] ["\\/bfnrt]
$uescape    : [\\] [u] [0-9A-Fa-f]{4}

NULL        : 'null'
TRUE        : 'true'
FALSE       : 'false'
NUMBER      : $int $frac? $exp?
STRING      : ["] ( $char | $escape | $uescape )* ["]
SYMBOL      : [{}\[\]:,]
            !symbol
WHITESPACE  : [ \t\f\r\n]+
            !skip
"""

SYN = """
$pair       : STRING `:` value
$members    : $pair ( `,` $pair )*
$elements   : value ( `,` value )*

value       : object    | array
            | NUMBER    | STRING
            | TRUE      | FALSE
            | NULL
object      : `{` $members? `}`
array       : `[` $elements? `]`
"""

EXAMPLES = [
        "true",
        "[1, 2, 3, [4, 5, 6]]",
        """ {"type": "number", "value": 1.01e-3, "units": null, "more": {} } """,
]

scan = make_scan(LEX)
parse = make_parse(SYN)

for text in EXAMPLES:
    print "="*79
    print "INPUT:", text
    print
    print "TOKENS:"
    tokens = scan(text)
    for token in tokens:
        print token
    print
    print "SYNTAX:"
    syntax = parse(tokens)
    print syntax
    print