File: parsley_json.py

package info (click to toggle)
python-parsley 1.3-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,048 kB
  • sloc: python: 9,897; makefile: 127
file content (34 lines) | stat: -rw-r--r-- 1,417 bytes parent folder | download | duplicates (4)
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
from parsley import makeGrammar
jsonGrammar = r"""
ws = (' ' | '\r' | '\n' | '\t')*
object = ws '{' members:m ws '}' ws -> dict(m)
members = (pair:first (ws ',' pair)*:rest -> [first] + rest) | -> []
pair = ws string:k ws ':' value:v -> (k, v)
array = '[' elements:xs ws ']' -> xs
elements = (value:first (ws ',' value)*:rest -> [first] + rest) | -> []
value = ws (string | number | object | array
           | 'true'  -> True
           | 'false' -> False
           | 'null'  -> None)
string = '"' (escapedChar | ~'"' anything)*:c '"' -> ''.join(c)
escapedChar = '\\' (('"' -> '"')    |('\\' -> '\\')
                   |('/' -> '/')    |('b' -> '\b')
                   |('f' -> '\f')   |('n' -> '\n')
                   |('r' -> '\r')   |('t' -> '\t')
                   |('\'' -> '\'')  | escapedUnicode)
hexdigit = :x ?(x in '0123456789abcdefABCDEF') -> x
escapedUnicode = 'u' <hexdigit{4}>:hs -> unichr(int(hs, 16))
number = ('-' | -> ''):sign (intPart:ds (floatPart(sign ds)
                            | -> int(sign + ds)))
digit = :x ?(x in '0123456789') -> x
digits = <digit*>
digit1_9 = :x ?(x in '123456789') -> x
intPart = (digit1_9:first digits:rest -> first + rest) | digit
floatPart :sign :ds = <('.' digits exponent?) | exponent>:tail
                    -> float(sign + ds + tail)
exponent = ('e' | 'E') ('+' | '-')? digits

top = (object | array) ws
"""

JSONParser = makeGrammar(jsonGrammar, {})