Class: JSON::Stream::Parser

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

Overview

A streaming JSON parser that generates SAX-like events for state changes. Use the json gem for small documents. Use this for huge documents that won’t fit in memory.

Constant Summary collapse

BUF_SIZE =
512
CONTROL =
/[[:cntrl:]]/
WS =
/\s/
HEX =
/[0-9a-fA-F]/
DIGIT =
/[0-9]/
DIGIT_1_9 =
/[1-9]/
DIGIT_END =
/\d$/
TRUE_RE =
/[rue]/
FALSE_RE =
/[alse]/
NULL_RE =
/[ul]/
TRUE_KEYWORD =
'true'
FALSE_KEYWORD =
'false'
NULL_KEYWORD =
'null'
LEFT_BRACE =
'{'
RIGHT_BRACE =
'}'
LEFT_BRACKET =
'['
RIGHT_BRACKET =
']'
BACKSLASH =
'\\'
SLASH =
'/'
QUOTE =
'"'
COMMA =
','
COLON =
':'
ZERO =
'0'
MINUS =
'-'
PLUS =
'+'
POINT =
'.'
EXPONENT =
/[eE]/

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Parser

Create a new parser with an optional initialization block where we can register event callbacks. For example: parser = JSON::Stream::Parser.new do

start_document { puts "start document" }
end_document   { puts "end document" }
start_object   { puts "start object" }
end_object     { puts "end object" }
start_array    { puts "start array" }
end_array      { puts "end array" }
key            {|k| puts "key: #{k}" }
value          {|v| puts "value: #{v}" }

end



84
85
86
87
88
89
90
# File 'lib/json/stream/parser.rb', line 84

def initialize(&block)
  @state = :start_document
  @utf8 = Buffer.new
  @listeners = Hash.new {|h, k| h[k] = [] }
  @stack, @unicode, @buf, @pos = [], "", "", -1
  instance_eval(&block) if block_given?
end

Class Method Details

.parse(json) ⇒ Object

Parses a full JSON document from a String or an IO stream and returns the parsed object graph. For parsing small JSON documents with small memory requirements, use the json gem’s faster JSON.parse method instead.



44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/json/stream/parser.rb', line 44

def self.parse(json)
  stream = json.is_a?(String) ? StringIO.new(json) : json
  parser = Parser.new
  builder = Builder.new(parser)
  while (buf = stream.read(BUF_SIZE)) != nil
    parser << buf
  end
  raise ParserError, "unexpected eof" unless builder.result
  builder.result
ensure
  stream.close
end

Instance Method Details

#<<(data) ⇒ Object

Pass data into the parser to advance the state machine and generate callback events. This is well suited for an EventMachine receive_data loop.



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/json/stream/parser.rb', line 95

def <<(data)
  (@utf8 << data).each_char do |ch|
    @pos += 1
    case @state
    when :start_document
      case ch
      when LEFT_BRACE
        @state = :start_object
        @stack.push(:object)
        notify_start_document
        notify_start_object
      when LEFT_BRACKET
        @state = :start_array
        @stack.push(:array)
        notify_start_document
        notify_start_array
      when WS
        # ignore
      else
        error("Expected object or array start")
      end
    when :start_object
      case ch
      when RIGHT_BRACE
        end_container(:object)
      when QUOTE
        @state = :start_string
        @stack.push(:key)
      when WS
        # ignore
      else
        error("Expected object key start")
      end
    when :start_string
      case ch
      when QUOTE
        if @stack.pop == :string
          @state = :end_value
          notify_value(@buf)
        else # :key
          @state = :end_key
          notify_key(@buf)
        end
        @buf = ""
      when BACKSLASH
        @state = :start_escape
      when CONTROL
        error('Control characters must be escaped')
      else
        @buf << ch
      end
    when :start_escape
      case ch
      when QUOTE, BACKSLASH, SLASH
        @buf << ch
        @state = :start_string
      when B
        @buf << "\b"
        @state = :start_string
      when F
        @buf << "\f"
        @state = :start_string
      when N
        @buf << "\n"
        @state = :start_string
      when R
        @buf << "\r"
        @state = :start_string
      when T
        @buf << "\t"
        @state = :start_string
      when U
        @state = :unicode_escape
      else
        error("Expected escaped character")
      end
    when :unicode_escape
      case ch
      when HEX
        @unicode << ch
        if @unicode.size == 4
          codepoint = @unicode.slice!(0, 4).hex
          if codepoint >= 0xD800 && codepoint <= 0xDBFF
            error('Expected low surrogate pair half') if @stack[-1].is_a?(Fixnum)
            @state = :start_surrogate_pair
            @stack.push(codepoint)
          elsif codepoint >= 0xDC00 && codepoint <= 0xDFFF
            high = @stack.pop
            error('Expected high surrogate pair half') unless high.is_a?(Fixnum)
            pair = ((high - 0xD800) * 0x400) + (codepoint - 0xDC00) + 0x10000
            @buf << pair
            @state = :start_string
          else
            @buf << codepoint
            @state = :start_string
          end
        end
      else
        error('Expected unicode escape hex digit')
      end
    when :start_surrogate_pair
      case ch
      when BACKSLASH 
        @state = :start_surrogate_pair_u
      else
        error('Expected low surrogate pair half')
      end
    when :start_surrogate_pair_u
      case ch
      when U
        @state = :unicode_escape
      else
        error('Expected low surrogate pair half')
      end
    when :start_negative_number
      case ch
      when ZERO
        @state = :start_zero
        @buf << ch
      when DIGIT_1_9
        @state = :start_int
        @buf << ch
      else
        error('Expected 0-9 digit')
      end
    when :start_zero
      case ch
      when POINT
        @state = :start_float
        @buf << ch
      when EXPONENT
        @state = :start_exponent
        @buf << ch
      else
        @state = :end_value
        notify_value(@buf.to_i)
        @buf = ""
        @pos -= 1
        redo
      end
    when :start_float
      case ch
      when DIGIT
        @state = :in_float
        @buf << ch
      else
        error('Expected 0-9 digit')
      end
    when :in_float
      case ch
      when DIGIT
        @buf << ch
      when EXPONENT
        @state = :start_exponent
        @buf << ch
      else
        @state = :end_value
        notify_value(@buf.to_f)
        @buf = ""
        @pos -= 1
        redo
      end
    when :start_exponent
      case ch
      when MINUS, PLUS, DIGIT
        @state = :in_exponent
        @buf << ch
      else
        error('Expected +, -, or 0-9 digit')
      end
    when :in_exponent
      case ch
      when DIGIT
        @buf << ch
      else
        error('Expected 0-9 digit') unless @buf =~ DIGIT_END
        @state = :end_value
        num = @buf.include?('.') ? @buf.to_f : @buf.to_i
        notify_value(num)
        @buf = ""
        @pos -= 1
        redo
      end
    when :start_int
      case ch
      when DIGIT
        @buf << ch
      when POINT
        @state = :start_float
        @buf << ch
      when EXPONENT
        @state = :start_exponent
        @buf << ch
      else
        @state = :end_value
        notify_value(@buf.to_i)
        @buf = ""
        @pos -= 1
        redo
      end
    when :start_true
      keyword(TRUE_KEYWORD, true, TRUE_RE, ch)
    when :start_false
      keyword(FALSE_KEYWORD, false, FALSE_RE, ch)
    when :start_null
      keyword(NULL_KEYWORD, nil, NULL_RE, ch)
    when :end_key
      case ch
      when COLON
        @state = :key_sep
      when WS
        # ignore
      else
        error("Expected colon key separator")
      end
    when :key_sep
      start_value(ch)
    when :start_array
      case ch
      when RIGHT_BRACKET
        end_container(:array)
      when WS
        # ignore
      else
        start_value(ch)
      end
    when :end_value
      case ch
      when COMMA
        @state = :value_sep
      when RIGHT_BRACKET
        end_container(:array)
      when RIGHT_BRACE
        end_container(:object)
      when WS
        # ignore
      else
        error("Expected comma or object or array close")
      end
    when :value_sep
      if @stack[-1] == :object
        case ch
        when QUOTE
          @state = :start_string
          @stack.push(:key)
        when WS
          # ignore
        else
          error("Expected object key start")
        end
      else
        start_value(ch)
      end
    when :end_document
      error("Unexpected data") unless ch =~ WS
    end
  end
end