简体   繁体   中英

How to access a JSON array with params in RAILS

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM