| Module | JSON::Pure::Generator::GeneratorMethods::Hash |
| In: |
lib/json/pure/generator.rb
|
Returns a JSON string containing a JSON object, that is unparsed from this Hash instance. state is a JSON::State object, that can also be used to configure the produced JSON string output further. depth is used to find out nesting depth, to indent accordingly.
# File lib/json/pure/generator.rb, line 212
212: def to_json(state = nil, depth = 0, *)
213: if state
214: state = JSON.state.from_state(state)
215: state.check_max_nesting(depth)
216: json_check_circular(state) { json_transform(state, depth) }
217: else
218: json_transform(state, depth)
219: end
220: end
# File lib/json/pure/generator.rb, line 224
224: def json_check_circular(state)
225: if state and state.check_circular?
226: state.seen?(self) and raise JSON::CircularDatastructure,
227: "circular data structures not supported!"
228: state.remember self
229: end
230: yield
231: ensure
232: state and state.forget self
233: end
# File lib/json/pure/generator.rb, line 235
235: def json_shift(state, depth)
236: state and not state.object_nl.empty? or return ''
237: state.indent * depth
238: end
# File lib/json/pure/generator.rb, line 240
240: def json_transform(state, depth)
241: delim = ','
242: delim << state.object_nl if state
243: result = '{'
244: result << state.object_nl if state
245: result << map { |key,value|
246: s = json_shift(state, depth + 1)
247: s << key.to_s.to_json(state, depth + 1)
248: s << state.space_before if state
249: s << ':'
250: s << state.space if state
251: s << value.to_json(state, depth + 1)
252: }.join(delim)
253: result << state.object_nl if state
254: result << json_shift(state, depth)
255: result << '}'
256: result
257: end