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 from a JSON document. This is similar to using the json gem’s ‘JSON.parse` method.
Examples
parser = JSON::Stream::Parser.new
builder = JSON::Stream::Builder.new(parser)
parser << '{"answer": 42, "question": false}'
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
#initialize(parser) ⇒ Builder
Returns a new instance of Builder.
17 18 19 20 21 |
# File 'lib/json/stream/builder.rb', line 17 def initialize(parser) METHODS.each do |name| parser.send(name, &method(name)) end end |
Instance Attribute Details
#result ⇒ Object (readonly)
Returns the value of attribute result.
15 16 17 |
# File 'lib/json/stream/builder.rb', line 15 def result @result end |
Instance Method Details
#end_document ⇒ Object
29 30 31 |
# File 'lib/json/stream/builder.rb', line 29 def end_document @result = @stack.pop end |
#end_object ⇒ Object Also known as: end_array
37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/json/stream/builder.rb', line 37 def end_object return if @stack.size == 1 node = @stack.pop top = @stack[-1] case top when Hash top[@keys.pop] = node when Array top << node end end |
#key(key) ⇒ Object
56 57 58 |
# File 'lib/json/stream/builder.rb', line 56 def key(key) @keys << key end |
#start_array ⇒ Object
52 53 54 |
# File 'lib/json/stream/builder.rb', line 52 def start_array @stack.push([]) end |
#start_document ⇒ Object
23 24 25 26 27 |
# File 'lib/json/stream/builder.rb', line 23 def start_document @stack = [] @keys = [] @result = nil end |
#start_object ⇒ Object
33 34 35 |
# File 'lib/json/stream/builder.rb', line 33 def start_object @stack.push({}) end |
#value(value) ⇒ Object
60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/json/stream/builder.rb', line 60 def value(value) top = @stack[-1] case top when Hash top[@keys.pop] = value when Array top << value else @stack << value end end |