Class: JSON::Stream::Builder
- Inherits:
-
Object
- Object
- JSON::Stream::Builder
- 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
-
#result ⇒ Object
readonly
Returns the value of attribute result.
Instance Method Summary collapse
- #end_document ⇒ Object
- #end_object ⇒ Object (also: #end_array)
-
#initialize(parser) ⇒ Builder
constructor
A new instance of Builder.
- #key(key) ⇒ Object
- #start_array ⇒ Object
- #start_document ⇒ Object
- #start_object ⇒ Object
- #value(value) ⇒ Object
Constructor Details
Instance Attribute Details
#result ⇒ Object (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_document ⇒ Object
31 32 33 |
# File 'lib/json/stream/builder.rb', line 31 def end_document @result = @stack.pop.obj end |
#end_object ⇒ Object 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_array ⇒ Object
47 48 49 |
# File 'lib/json/stream/builder.rb', line 47 def start_array @stack.push(ArrayNode.new) end |
#start_document ⇒ Object
27 28 29 |
# File 'lib/json/stream/builder.rb', line 27 def start_document @stack, @result = [], nil end |
#start_object ⇒ Object
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 |