I have a post request to a Rails JSON API server that looks like that:
POST /api/posts.json HTTP/1.1
Accepts: application/json
X-API-KEY: 7d867d16a5e25337b6d7857965f812bee73b76ac
Content-Length: 288
Content-Type: multipart/form-data; boundary=syoYQUQsGwI2XqShQimFdv2QSe-_GYbjVx40T1kS
Host: 10.0.2.2:3000
Connection: Keep-Alive
User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)
--syoYQUQsGwI2XqShQimFdv2QSe-_GYbjVx40T1kS
Content-Disposition: form-data; name="DATA"
Content-Type: application/json; charset=UTF-8
Content-Transfer-Encoding: 8bit
{"tags":["dffdff"],"location_id":3,"post":{"content":"test #dffdff"}}
--syoYQUQsGwI2XqShQimFdv2QSe-_GYbjVx40T1kS--
how do I access the JSON params ?
if I write params[:DATA] to log I see the attributes, but everything nested is empty (such as params[:DATA][:post] or params[:DATA][:tags]
UPDATE:
when i’m trying to do
Rails.logger.debug(params[:DATA])
I get
{"tags":["dffdff"],"location_id":3,"post":{"content":"test #dffdff"}}
but when I try
Rails.logger.debug(params[:DATA][:post])
I get
TypeError (can't convert Symbol into Integer):
app/controllers/api/posts_controller.rb:19:in `[]'
app/controllers/api/posts_controller.rb:19:in `create'
Your issue is that
params[:DATA]is a string, but you are treating it like a hash.You’ll need to parse the JSON-string into a Ruby hash, like so:
If you want to use symbols in the hash, i.e.
[:post], then you can do:NB. If you want to test this out in a ruby console, rather than using
params[:DATA], you can init data on the first line with: