Reputation: 20538
I got a JSON object that I have generated via Rails 3 (via my API). I need to either put a named surrounding tag around it or loose the first "layer". I know it sounds very strange, but I cannot loop it in the client.
This is the 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": "[email protected]",
"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": "[email protected]",
"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": "[email protected]",
"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 protected]",
"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": "[email protected]",
"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": "[email protected]",
"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": "[email protected]",
"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 protected]",
"value_2": null,
"id": 7,
"value_3": null,
"user_id": 1,
"value_4": null,
"desc": "Hello world",
"privacy": null
}
]
This is how I try to loop through it in the client.
<% @array['email'].each do |item| %>
<%= item['value_1'] %>
<% end %>
Upvotes: 0
Views: 248
Reputation: 3644
Try the following in config > initializers > wrap_parameters.rb
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActionController::Base.wrap_parameters format: [:json]
# Disable root element in JSON by default.
if defined?(ActiveRecord)
ActiveRecord::Base.include_root_in_json = false
end
By setting the "include_root_in_json" to false, it should get you the desired output
Upvotes: 1