Last active
September 28, 2015 05:37
-
-
Save NigelThorne/1392475 to your computer and use it in GitHub Desktop.
JSON Parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'parslet' | |
#This needs a few more 'as' calls to annotate the output | |
class JSONParser < Parslet::Parser | |
rule(:space) { match('[\s\n]').repeat(1)} | |
rule(:space?) { space.maybe } | |
rule(:digit) { match('[0-9]') } | |
rule(:hexdigit) { match('[0-9a-fA-F]') } | |
rule(:comma) { space? >> str(',') >> space? } | |
rule(:colon) { space? >> str(':') >> space? } | |
rule(:number) { space? >> str('-').maybe >> | |
(str('0') | (match('[1-9]') >> digit.repeat)) >> | |
(str('.') >> digit.repeat).maybe >> | |
((str('e')| str('E')) >> (str('+')|str('-')).maybe >> digit.repeat ).maybe } | |
rule(:escaped_character) { str('\\') >> (match('["\\\\/bfnrt]') | (str('u') >> hexdigit.repeat(4,4))) } | |
rule(:string){ | |
str('"') >> ( | |
escaped_character | str('"').absent? >> any | |
).repeat.as(:string) >> str('"') | |
} | |
rule(:value){ | |
(string | | |
number | | |
object | | |
array | | |
str('true').as(:true) | | |
str('false').as(:false) | | |
str('null').as(:null)).as(:val) | |
} | |
rule(:entry) { string >> colon >> value } | |
rule(:pair_list) { entry>> (comma >> entry).repeat } | |
rule(:object) { str('{') >> space? >> pair_list.maybe >> space? >> str('}') } | |
rule(:value_list) { value >> (comma >> value).repeat } | |
rule(:array) { str('[') >> space? >> value_list.maybe >> space? >> str(']')} | |
rule(:json) { space? >> value >> space?} | |
root(:json) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I just found someone else has written one too.. https://gist.github.com/966020