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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
##############################################################################
# Name: json.py
# Purpose: Implementation of a simple JSON parser in arpeggio.
# Author: Igor R. Dejanovic <igor DOT dejanovic AT gmail DOT com>
# Copyright: (c) 2009-2014 Igor R. Dejanovic <igor DOT dejanovic AT gmail DOT com>
# License: MIT License
#
# This example is based on jsonParser.py from the pyparsing project
# (see http://pyparsing.wikispaces.com/).
##############################################################################
from __future__ import unicode_literals
json_bnf = """
object
{ members }
{}
members
string : value
members , string : value
array
[ elements ]
[]
elements
value
elements , value
value
string
number
object
array
true
false
null
"""
from arpeggio import *
from arpeggio import RegExMatch as _
def TRUE(): return "true"
def FALSE(): return "false"
def NULL(): return "null"
def jsonString(): return '"', _('[^"]*'),'"'
def jsonNumber(): return _('-?\d+((\.\d*)?((e|E)(\+|-)?\d+)?)?')
def jsonValue(): return [jsonString, jsonNumber, jsonObject, jsonArray, TRUE, FALSE, NULL]
def jsonArray(): return "[", Optional(jsonElements), "]"
def jsonElements(): return jsonValue, ZeroOrMore(",", jsonValue)
def memberDef(): return jsonString, ":", jsonValue
def jsonMembers(): return memberDef, ZeroOrMore(",", memberDef)
def jsonObject(): return "{", Optional(jsonMembers), "}"
def jsonFile(): return jsonObject, EOF
testdata = """
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList":
{
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"TrueValue": true,
"FalseValue": false,
"Gravity": -9.8,
"LargestPrimeLessThan100": 97,
"AvogadroNumber": 6.02E23,
"EvenPrimesGreaterThan2": null,
"PrimesLessThan10" : [2,3,5,7],
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML", "markup"],
"EmptyDict": {},
"EmptyList" : []
}
}
}
}
"""
def main(debug=False):
# Creating parser from parser model.
parser = ParserPython(jsonFile, debug=debug)
# Parse json string
parse_tree = parser.parse(testdata)
if __name__ == "__main__":
# In debug mode dot (graphviz) files for parser model
# and parse tree will be created for visualization.
# Checkout current folder for .dot files.
main(debug=True)