Class | Hash |
In: |
lib/json.rb
|
Parent: | Object |
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.rb, line 537 537: def to_json(state = nil, depth = 0) 538: state = JSON::State.from_state(state) 539: json_check_circular(state) { json_transform(state, depth) } 540: end
# File lib/json.rb, line 544 544: def json_check_circular(state) 545: if state 546: state.seen?(self) and raise JSON::CircularDatastructure, 547: "circular data structures not supported!" 548: state.remember self 549: end 550: yield 551: ensure 552: state and state.forget self 553: end
# File lib/json.rb, line 555 555: def json_shift(state, depth) 556: state and not state.object_nl.empty? or return '' 557: state.indent * depth 558: end
# File lib/json.rb, line 560 560: def json_transform(state, depth) 561: delim = ',' 562: delim << state.object_nl if state 563: result = '{' 564: result << state.object_nl if state 565: result << map { |key,value| 566: json_shift(state, depth + 1) << 567: key.to_s.to_json(state, depth + 1) << 568: ':' << state.space << value.to_json(state, depth + 1) 569: }.join(delim) 570: result << state.object_nl if state 571: result << json_shift(state, depth) 572: result << '}' 573: result 574: end