我有一个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帖子数据如下:
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
答案 0 :(得分: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.parse
返回的哈希中,attachments
键应为字符串('attachments'
),而不是符号(:attachments
)。更新了上面的答案。
答案 1 :(得分:1)
请尝试:email_payload ['attachments'] [0] [3]
看来问题可能是:附件(符号)和'附件'(字符串)之间的区别。