1"""Simple example of a json parser with comment support""" 2from __future__ import print_function 3 4from simpleparse.common import numbers, strings, comments 5 6declaration = r''' 7object := ts,'{',!,ts,(member,sep?)*,'}' 8 9member := string,ts,':',ts,value,ts 10array := ts,'[',!,ts,(value,sep?)*,']',ts 11 12>value< := js_string/object/array/true/false/null/float/int_w_exp/int 13 14int_w_exp := int,[eE],int 15 16>js_string< := string_single_quote/string_double_quote 17true := 'true' 18false := 'false' 19null := 'null' 20 21<ts> := ([ \t\n\r]+/comment)* 22<comment> := slashslash_comment/c_nest_comment 23<sep> := (','?,ts) 24''' 25from simpleparse.parser import Parser 26from simpleparse.dispatchprocessor import * 27import pprint 28 29class Processor( DispatchProcessor ): 30 def object( self, info, buffer ): 31 (tag,start,stop,children) = info 32 obj = {} 33 for key,value in dispatchList( self, children, buffer ): 34 obj[key] = value 35 return obj 36 def member( self, info, buffer ): 37 (tag,start,stop,children) = info 38 return dispatchList( self, children, buffer ) 39 def array( self, info, buffer ): 40 (tag,start,stop,children) = info 41 return dispatchList( self, children, buffer ) 42 def int_w_exp( self, info, buffer ): 43 (tag,start,stop,(a,b)) = info 44 base = dispatch( self, a, buffer ) 45 exp = dispatch( self, b, buffer ) 46 return base ** exp 47 int = numbers.IntInterpreter() 48 float = numbers.FloatInterpreter() 49 string = strings.StringInterpreter() 50 string_double_quote = strings.StringInterpreter() 51 string_single_quote = string_double_quote 52 def true( self, tag, buffer ): 53 return True 54 def false( self, tag, buffer ): 55 return False 56 def null( self, tag, buffer ): 57 return None 58 59 60parser = Parser( declaration, "object" ) 61if __name__ =="__main__": 62 import sys,json 63 print(json.dumps( 64 parser.parse( open(sys.argv[1]).read(), processor=Processor()) 65 )) 66