From: tho_mica_l Date: 2008-02-04T01:24:57+09:00 Subject: Re: Parsing JSON (#155) I liked this quiz because it made me look into treetop, ragel and some other libraries I wanted to examine a little bit closer for quite a while now. Anyway, for my (official) solution I took the easy road and rely on ruby to do the actual work. My solution is ruby19 only, since I used the opportunity to explore some of the new regexp features. Since it uses eval(), there is a possibility for ruby code injection like the ultimatively relieving "#{`sudo rm - rf /`}". I think my solution catches such attacks though. BTW, what do you all think should be the canonic output of the following JSON snippet: json1 = <:)| (?,\s*[}\]])| ,| (?"([^"\\]++|\\(u[0-9a-fA-F]{4}|[bfnrt"\/\\]))*")| -?(0|[1-9]\d*+)(\.\d++)?([Ee][+-]?\d++)?(?=\D|$)| true| false| (?null)| [[:space:][:cntrl:]]++| (?.++) /xmu def parse(json) ruby = json.gsub(RXE) do |t| m = $~ if m['invalid'] then invalid(m['invalid']) elsif m['null'] then 'nil' elsif m['name_sep'] then '=>' elsif m['string'] then m['string'].gsub(/#/, '\\\\#') else t end end begin return eval(ruby) rescue Exception => e invalid(json) end end def invalid(string) raise RuntimeError, 'Invalid JSON: %s' % string end end if __FILE__ == $0 a = ARGV.join p a p JSONParser.new.parse(a) end