Class: JSON::Parser

Inherits:
StringScanner
  • Object
show all
Defined in:
lib/parser.rb

Overview

This class implements the JSON parser that is used to parse a JSON string into a Ruby data structure.

Constant Summary collapse

STRING =
/"((?:[^"\\]|\\.)*)"/
INTEGER =
/-?\d+/
FLOAT =
/-?\d+\.(\d*)(?i:e[+-]?\d+)?/
OBJECT_OPEN =
/\{/
OBJECT_CLOSE =
/\}/
ARRAY_OPEN =
/\[/
ARRAY_CLOSE =
/\]/
PAIR_DELIMITER =
/:/
COLLECTION_DELIMITER =
/,/
TRUE =
/true/
FALSE =
/false/
NULL =
/null/
IGNORE =
%r(
  (?:
    //[^\n\r]*[\n\r]| # line comments
    /\*               # c-style comments
      (?:
        [^*/]|        # normal chars
        /[^*]|        # slashes that do not start a nested comment
        \*[^/]|       # asterisks that do not end this comment
        /(?=\*/)      # single slash before this comment's end
      )*
    \*/               # the end of this comment
    |\s+              # whitespaces
  )+
)mx
UNPARSED =
Object.new

Instance Method Summary collapse

Instance Method Details

#parseObject

Parses the current JSON string and returns the complete data structure as a result.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/parser.rb', line 36

def parse
  reset
  until eos?
    case
    when scan(ARRAY_OPEN)
      return parse_array
    when scan(OBJECT_OPEN)
      return parse_object
    when skip(IGNORE)
      ;
    when !((value = parse_value).equal? UNPARSED)
      return value
    else
      raise ParserError, "source '#{peek(20)}' not in JSON!"
    end
  end
end