0

我有一个 Rails 3 应用程序,我正在使用以下代码来解析 JSON 帖子:

email_payload = JSON.parse(params[:payload])
Result.create(:from => email_payload['from'], :from_name => email_payload['from_name'], :from_address => email_payload['from_address'], :date => email_payload['date'], :html_body => email_payload['html_body'], :priority => email_payload['priority'], :spam_status => email_payload['spam_status'], :subject => email_payload['subject'])

JSON post数据如下:

payload{ "address_identifier": null, "attachments": [ [ "twitter.png", "image/png", 3029, "http://api.deliverhq.com/api/incoming/attachment/7gdd71wo75/5772412/0" ] ], "cc": null, "date": "Thu, 25 Oct 2012 22:04:20 +0100"

我正在尝试研究如何解析 URL,在这种情况下http://api.deliverhq.com/api/incoming/attachment/7gdd71wo75/5772412/0,然后将 URL 输入数据库。

:url => email_payload['attachments']

将不起作用,因为附件中有多个值,并且:

email_attachments_payload = JSON.parse(params[:payload][:attachments])
:url => email_attachments_payload['URL']

将不起作用,因为 URL 没有标识符。对于这个特定的应用程序,应该只有一个附件,因此如果可能的话,选择 .first 可能是一个选项。

任何指针将不胜感激!

更新:

添加:

email_payload[:attachments][0][4]

导致以下异常错误:

NoMethodError: undefined method []' for nil:NilClass

更新 2

def receive_fax
    if request.get?
        render :text => "hello"
    elsif request.post?   
      email_payload = JSON.parse(params[:payload])     
      Fax.create(:from => email_payload['from'], :from_name => email_payload['from_name'], :from_address => email_payload['from_address'], :date => email_payload['date'], :html_body => email_payload['html_body'], :priority => email_payload['priority'], :spam_status => email_payload['spam_status'], :subject => email_payload['subject'], :fax => email_payload[:attachments][0][3])
      render :text => "success"
    else
      render :text => "error"
    end
  end
4

2 回答 2

2

在 irb 中:

require 'json'

email_payload = JSON.parse('{ "address_identifier": null, "attachments": [ [ "twitter.png", "image/png", 3029, "http://api.deliverhq.com/api/incoming/attachment/7gdd71wo75/5772412/0" ] ], "cc": null, "date": "Thu, 25 Oct 2012 22:04:20 +0100" }')
#=> {"address_identifier"=>nil, "attachments"=>[["twitter.png", "image/png", 3029, "http://api.deliverhq.com/api/incoming/attachment/7gdd71wo75/5772412/0"]], "cc"=>nil, "date"=>"Thu, 25 Oct 2012 22:04:20 +0100"}
email_payload['attachments'][0][3]
#=> "http://api.deliverhq.com/api/incoming/attachment/7gdd71wo75/5772412/0"

如果这不起作用,那么还有其他一些您在上面没有描述的事情。

更新:在从 返回的哈希中JSON.parseattachments键应该是字符串 ( 'attachments'),而不是符号 ( :attachments)。更新了我上面的答案。

于 2012-10-28T14:05:29.810 回答
1

请尝试:email_payload['attachments'][0][3]

看来问题可能是 :attachments (一个符号)和 'attachments' (一个字符串)之间的区别。

于 2012-10-28T14:36:30.063 回答