Reputation:
For my API in RAILS I would like to access a JSON array for some operations and save it in an array.
Something like this: JSON [{"consumption":2.3e-06,"date":"00:15"},{"consumption":1.3e-06,"date":"00:30"}]
This JSON is sent from curl
and in the controller i want to do something like this:
a[0] = params[0][:consumption]
Here 0 should be different(0,1,2...) to access the different positions in my JSON array. (1 consumption, 2 consumption and so on)
But I dont know how to do manage this with params
Any help would be nice.
Upvotes: 3
Views: 2138
Reputation: 4515
you will not be able to access this JSON array in way you expect(params[0]
).
first - params
object is a wrapper on data sent to server (it also keeps current controller/action name). You have to wrap your JSON array in a param of name you would like to access it on server.
For example, you may POST your data and the payload may look: { consumption_data: array_from_your_post }.
Then this array will be accessible by invoking params[:consumption_data]
in your controller. First item of array is then params[:consumption_data][0]
and so on.
How to send your json via curl?
curl -H "Content-Type: application/json" -X POST -d '{"consumption_data": [here_put_your_items]}' http://localhost:3000/action_name
Upvotes: 7