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 481 481: def to_json(state = nil, depth = 0) 482: state = JSON::State.from_state(state) 483: json_check_circular(state) { json_transform(state, depth) } 484: end
# File lib/json.rb, line 488 488: def json_check_circular(state) 489: if state 490: state.seen?(self) and raise JSON::CircularDatastructure, 491: "circular data structures not supported!" 492: state.remember self 493: end 494: yield 495: ensure 496: state and state.forget self 497: end
# File lib/json.rb, line 499 499: def json_shift(state, depth) 500: state and not state.object_nl.empty? or return '' 501: state.indent * depth 502: end
# File lib/json.rb, line 504 504: def json_transform(state, depth) 505: delim = ',' 506: delim << state.object_nl if state 507: result = '{' 508: result << state.object_nl if state 509: result << map { |key,value| 510: json_shift(state, depth + 1) << 511: key.to_s.to_json(state, depth + 1) << 512: ':' << state.space << value.to_json(state, depth + 1) 513: }.join(delim) 514: result << state.object_nl if state 515: result << json_shift(state, depth) 516: result << '}' 517: result 518: end