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 237 237: def to_json(state = nil, depth = 0, *) 238: if state 239: state = JSON.state.from_state(state) 240: state.check_max_nesting(depth) 241: json_check_circular(state) { json_transform(state, depth) } 242: else 243: json_transform(state, depth) 244: end 245: end
# File lib/json/pure/generator.rb, line 249 249: def json_check_circular(state) 250: if state and state.check_circular? 251: state.seen?(self) and raise JSON::CircularDatastructure, 252: "circular data structures not supported!" 253: state.remember self 254: end 255: yield 256: ensure 257: state and state.forget self 258: end
# File lib/json/pure/generator.rb, line 260 260: def json_shift(state, depth) 261: state and not state.object_nl.empty? or return '' 262: state.indent * depth 263: end
# File lib/json/pure/generator.rb, line 265 265: def json_transform(state, depth) 266: delim = ',' 267: if state 268: delim << state.object_nl 269: result = '{' 270: result << state.object_nl 271: result << map { |key,value| 272: s = json_shift(state, depth + 1) 273: s << key.to_s.to_json(state, depth + 1) 274: s << state.space_before 275: s << ':' 276: s << state.space 277: s << value.to_json(state, depth + 1) 278: }.join(delim) 279: result << state.object_nl 280: result << json_shift(state, depth) 281: result << '}' 282: else 283: result = '{' 284: result << map { |key,value| 285: key.to_s.to_json << ':' << value.to_json 286: }.join(delim) 287: result << '}' 288: end 289: result 290: end