Class: JSON::Stream::Builder

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

Overview

A parser listener that builds a full, in memory, object graph from a JSON document. Typically, we would use the json gem’s JSON.parse() method when we have the full JSON document because it’s much faster than this. JSON::Stream is typically used when we have a huge JSON document streaming to us and we don’t want to hold the entire parsed object in memory. Regardless, this is a good example of how to write parser callbacks.

parser = JSON::Stream::Parser.new builder = JSON::Stream::Builder.new(parser) parser << json obj = builder.result

Constant Summary collapse

METHODS =
%w[start_document end_document start_object end_object start_array end_array key value]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parser) ⇒ Builder

Returns a new instance of Builder.



21
22
23
24
25
# File 'lib/json/stream/builder.rb', line 21

def initialize(parser)
  METHODS.each do |name|
    parser.send(name, &method(name))
  end
end

Instance Attribute Details

#resultObject (readonly)

Returns the value of attribute result.



19
20
21
# File 'lib/json/stream/builder.rb', line 19

def result
  @result
end

Instance Method Details

#end_documentObject



31
32
33
# File 'lib/json/stream/builder.rb', line 31

def end_document
  @result = @stack.pop.obj
end

#end_objectObject Also known as: end_array



39
40
41
42
43
44
# File 'lib/json/stream/builder.rb', line 39

def end_object
  unless @stack.size == 1
    node = @stack.pop
    @stack[-1] << node.obj
  end
end

#key(key) ⇒ Object



51
52
53
# File 'lib/json/stream/builder.rb', line 51

def key(key)
  @stack[-1] << key
end

#start_arrayObject



47
48
49
# File 'lib/json/stream/builder.rb', line 47

def start_array
  @stack.push(ArrayNode.new)
end

#start_documentObject



27
28
29
# File 'lib/json/stream/builder.rb', line 27

def start_document
  @stack, @result = [], nil
end

#start_objectObject



35
36
37
# File 'lib/json/stream/builder.rb', line 35

def start_object
  @stack.push(ObjectNode.new)
end

#value(value) ⇒ Object



55
56
57
# File 'lib/json/stream/builder.rb', line 55

def value(value)
  @stack[-1] << value
end