ruby on rails 3 - Problems parsing generated JSON -
i got json object have generated via rails 3 (via api). need either put named surrounding tag around or loose first "layer". know sounds strange, cannot loop in client.
this parsing code:
@results = restclient.get "http://localhost:5000/emails?token=#{get_token}", :accept => :json @array = json.parse(@results);
turn this:
[ { "email": { "created_at": "2011-03-02t12:23:59z", "updated_at": "2011-03-02t12:23:59z", "value_1": "intevisa@sss.com", "value_2": null, "id": 4, "value_3": null, "user_id": 1, "value_4": null, "desc": "intevisa", "privacy": null } }, { "email": { "created_at": "2011-03-02t15:19:39z", "updated_at": "2011-03-02t15:19:39z", "value_1": "another@yahoo.com", "value_2": null, "id": 5, "value_3": null, "user_id": 1, "value_4": null, "desc": "some text", "privacy": null } }, { "email": { "created_at": "2011-03-02t15:20:17z", "updated_at": "2011-03-02t15:20:17z", "value_1": "my@email.com", "value_2": null, "id": 6, "value_3": null, "user_id": 1, "value_4": null, "desc": "some text", "privacy": null } }, { "email": { "created_at": "2011-03-02t15:21:03z", "updated_at": "2011-03-02t15:21:03z", "value_1": "an email@google.com", "value_2": null, "id": 7, "value_3": null, "user_id": 1, "value_4": null, "desc": "hello world", "privacy": null } } ]
into this:
[ "email": { "created_at": "2011-03-02t12:23:59z", "updated_at": "2011-03-02t12:23:59z", "value_1": "intevisa@sss.com", "value_2": null, "id": 4, "value_3": null, "user_id": 1, "value_4": null, "desc": "intevisa", "privacy": null }, "email": { "created_at": "2011-03-02t15:19:39z", "updated_at": "2011-03-02t15:19:39z", "value_1": "another@yahoo.com", "value_2": null, "id": 5, "value_3": null, "user_id": 1, "value_4": null, "desc": "some text", "privacy": null }, "email": { "created_at": "2011-03-02t15:20:17z", "updated_at": "2011-03-02t15:20:17z", "value_1": "my@email.com", "value_2": null, "id": 6, "value_3": null, "user_id": 1, "value_4": null, "desc": "some text", "privacy": null }, "email": { "created_at": "2011-03-02t15:21:03z", "updated_at": "2011-03-02t15:21:03z", "value_1": "an email@google.com", "value_2": null, "id": 7, "value_3": null, "user_id": 1, "value_4": null, "desc": "hello world", "privacy": null } ]
this how try loop through in client.
<% @array['email'].each |item| %> <%= item['value_1'] %> <% end %>
try following in config > initializers > wrap_parameters.rb
# enable parameter wrapping json. can disable setting :format empty array. actioncontroller::base.wrap_parameters format: [:json] # disable root element in json default. if defined?(activerecord) activerecord::base.include_root_in_json = false end
by setting "include_root_in_json" false, should desired output
Comments
Post a Comment