I have a Rails 3 application and I am using the following code to parse a JSON post:
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'])
The JSON post data is as follows:
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"
I am trying to work out how to parse the URL, in this case http://api.deliverhq.com/api/incoming/attachment/7gdd71wo75/5772412/0, and then enter the URL into the database.
:url => email_payload['attachments']
won't work because there is multiple values within attachment and:
email_attachments_payload = JSON.parse(params[:payload][:attachments])
:url => email_attachments_payload['URL']
won't work because the URL doesn't have an identifier. For this particular application there should only ever be one attachment, therefore selecting .first may be an option if that's possible.
Any pointers would be appreciated!
UPDATE:
Adding:
email_payload[:attachments][0][4]
results in the following exception error:
NoMethodError: undefined method []' for nil:NilClass
UPDATE 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
attachmentandattachments, is it singular or plural?email_payload[:attachments]is a 1-element array with a 4-element array in it, the last of which is a URL. What you want is to get that URL? Can't you just useemail_payload[:attachments][0][4]? If not then you have to be more specific about the constraints.TypeError: can't convert Symbol into IntegerNoMethodError: undefined method[]' for nil:NilClass`email_payload[:attachments][0][3]. It works fine in the console.