/* * call-seq: to_json(state = nil, depth = 0) * * 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. */ static VALUE mHash_to_json(int argc, VALUE *argv, VALUE self) { VALUE Vstate, Vdepth, result; long depth; rb_scan_args(argc, argv, "02", &Vstate, &Vdepth); depth = NIL_P(Vdepth) ? 0 : FIX2LONG(Vdepth); if (NIL_P(Vstate)) { long len = RHASH_SIZE(self); result = rb_str_buf_new(len); rb_str_buf_cat2(result, "{"); rb_hash_foreach(self, hash_to_json_i, result); rb_str_buf_cat2(result, "}"); } else { GET_STATE(Vstate); check_max_nesting(state, depth); if (state->check_circular) { VALUE self_id = rb_obj_id(self); if (RTEST(rb_hash_aref(state->seen, self_id))) { rb_raise(eCircularDatastructure, "circular data structures not supported!"); } rb_hash_aset(state->seen, self_id, Qtrue); result = mHash_json_transfrom(self, Vstate, LONG2FIX(depth)); rb_hash_delete(state->seen, self_id); } else { result = mHash_json_transfrom(self, Vstate, LONG2FIX(depth)); } } OBJ_INFECT(result, self); FORCE_UTF8(result); return result; }