Ruby on rails 访问多部分json的参数
我有一个对Rails JSON API服务器的post请求,如下所示:Ruby on rails 访问多部分json的参数,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我有一个对Rails JSON API服务器的post请求,如下所示: 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 H
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--
如何访问JSON参数
如果我将params[:DATA]写入日志,我会看到属性,但嵌套的所有内容都是空的(例如params[:DATA][:post]或params[:DATA][:tags)
更新:
当我试着去做的时候
Rails.logger.debug(params[:DATA])
我明白了
{"tags":["dffdff"],"location_id":3,"post":{"content":"test #dffdff"}}
TypeError (can't convert Symbol into Integer):
app/controllers/api/posts_controller.rb:19:in `[]'
app/controllers/api/posts_controller.rb:19:in `create'
但是当我尝试的时候
Rails.logger.debug(params[:DATA][:post])
我明白了
{"tags":["dffdff"],"location_id":3,"post":{"content":"test #dffdff"}}
TypeError (can't convert Symbol into Integer):
app/controllers/api/posts_controller.rb:19:in `[]'
app/controllers/api/posts_controller.rb:19:in `create'
您的问题是
params[:DATA]
是一个字符串,但您将其视为散列
您需要将JSON字符串解析为Ruby哈希,如下所示:
data = JSON.parse(params[:DATA])
puts data['post']
如果要在哈希中使用符号,即[:post]
,则可以执行以下操作:
data = data.with_indifferent_access
puts data[:post]
注意:如果您想在ruby控制台中测试这一点,而不是使用params[:DATA]
,您可以使用以下命令在第一行初始化数据:
data = JSON.parse('{"tags":["dffdff"],"location_id":3,"post":{"content":"test #dffdff"}} ')
您的问题是
params[:DATA]
是一个字符串,但您将其视为散列
您需要将JSON字符串解析为Ruby哈希,如下所示:
data = JSON.parse(params[:DATA])
puts data['post']
如果要在哈希中使用符号,即[:post]
,则可以执行以下操作:
data = data.with_indifferent_access
puts data[:post]
注意:如果您想在ruby控制台中测试这一点,而不是使用params[:DATA]
,您可以使用以下命令在第一行初始化数据:
data = JSON.parse('{"tags":["dffdff"],"location_id":3,"post":{"content":"test #dffdff"}} ')
params[:DATA]
是字符串、数组还是其他类型?它是多部分部分的表单名称,您可以在questionDoes params[:DATA]['tags'中看到完整的请求工作?我不确定rails是否通过和_interference_access
stuffno运行解析的json。它不工作。我如何访问这些json参数?我用日志输出更新了这个问题,即参数[:DATA]
字符串、数组或其他类型?它是多部分部分的表单名称,您可以在questionDoes参数[:DATA]['tags'中看到完整的请求工作?我不确定rails是否运行经过解析的json,尽管使用_interference _accessstuffno它不工作。我如何访问这些json参数?我用日志outputnb更新了这个问题。这是用rails 3.2.3、ruby 1.9.3p125nb测试的。这是用rails 3.2.3、ruby 1.9.3p125测试的