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.

Examples

parser = JSON::Stream::Parser.new
parser.key {|key| puts key }
parser.value {|value| puts value }
parser << '{"answer":'
parser << ' 42}'

Constant Summary collapse

BUF_SIZE =
4096
CONTROL =
/[\x00-\x1F]/
WS =
/[ \n\t\r]/
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.

Examples

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


91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/json/stream/parser.rb', line 91

def initialize(&block)
  @state = :start_document
  @utf8 = Buffer.new
  @listeners = {
    start_document: [],
    end_document: [],
    start_object: [],
    end_object: [],
    start_array: [],
    end_array: [],
    key: [],
    value: []
  }

  # Track parse stack.
  @stack = []
  @unicode = ""
  @buf = ""
  @pos = -1

  # Register any observers in the block.
  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.

json - The String or IO containing JSON data.

Examples

JSON::Stream::Parser.parse('{"hello": "world"}')
# => {"hello": "world"}

Raises a JSON::Stream::ParserError if the JSON data is malformed.

Returns a Hash.



63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/json/stream/parser.rb', line 63

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
  parser.finish
  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.

data - The String of partial JSON data to parse.

Raises a JSON::Stream::ParserError if the JSON data is malformed.

Returns nothing.



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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/json/stream/parser.rb', line 156

def <<(data)
  (@utf8 << data).each_char do |ch|
    @pos += 1
    case @state
    when :start_document
      start_value(ch)
    when :start_object
      case ch
      when QUOTE
        @state = :start_string
        @stack.push(:key)
      when RIGHT_BRACE
        end_container(:object)
      when WS
        # ignore
      else
        error('Expected object key start')
      end
    when :start_string
      case ch
      when QUOTE
        if @stack.pop == :string
          end_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
        end_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
        end_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
        end_value(@buf.to_f)
        @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
        end_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_BRACE
        end_container(:object)
      when RIGHT_BRACKET
        end_container(:array)
      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

#end_array(&block) ⇒ Object



135
136
137
# File 'lib/json/stream/parser.rb', line 135

def end_array(&block)
  @listeners[:end_array] << block
end

#end_document(&block) ⇒ Object



119
120
121
# File 'lib/json/stream/parser.rb', line 119

def end_document(&block)
  @listeners[:end_document] << block
end

#end_object(&block) ⇒ Object



127
128
129
# File 'lib/json/stream/parser.rb', line 127

def end_object(&block)
  @listeners[:end_object] << block
end

#finishObject

Drain any remaining buffered characters into the parser to complete the parsing of the document.

This is only required when parsing a document containing a single numeric value, integer or float. The parser has no other way to detect when it should no longer expect additional characters with which to complete the parse, so it must be signaled by a call to this method.

If you’re parsing more typical object or array documents, there’s no need to call ‘finish` because the parse will complete when the final closing `]` or `}` character is scanned.

Raises a JSON::Stream::ParserError if the JSON data is malformed.

Returns nothing.



410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# File 'lib/json/stream/parser.rb', line 410

def finish
  # Partial multi-byte character waiting for completion bytes.
  error('Unexpected end-of-file') unless @utf8.empty?

  # Partial array, object, or string.
  error('Unexpected end-of-file') unless @stack.empty?

  case @state
  when :end_document
    # done, do nothing
  when :in_float
    end_value(@buf.to_f)
  when :in_exponent
    error('Unexpected end-of-file') unless @buf =~ DIGIT_END
    end_value(@buf.to_f)
  when :start_zero
    end_value(@buf.to_i)
  when :start_int
    end_value(@buf.to_i)
  else
    error('Unexpected end-of-file')
  end
end

#key(&block) ⇒ Object



139
140
141
# File 'lib/json/stream/parser.rb', line 139

def key(&block)
  @listeners[:key] << block
end

#start_array(&block) ⇒ Object



131
132
133
# File 'lib/json/stream/parser.rb', line 131

def start_array(&block)
  @listeners[:start_array] << block
end

#start_document(&block) ⇒ Object



115
116
117
# File 'lib/json/stream/parser.rb', line 115

def start_document(&block)
  @listeners[:start_document] << block
end

#start_object(&block) ⇒ Object



123
124
125
# File 'lib/json/stream/parser.rb', line 123

def start_object(&block)
  @listeners[:start_object] << block
end

#value(&block) ⇒ Object



143
144
145
# File 'lib/json/stream/parser.rb', line 143

def value(&block)
  @listeners[:value] << block
end