2011-04-17 124 views
2

我想使用Ruby接收JSON對象。我寫這樣的:Ruby:接收並打印JSON對象

require 'sinatra' 
require 'json' 

post '/' do 
    push = JSON.parse(params[:payload]) 
    "I got some JSON: #{push.inspect}" 
end 

而且我發送:

var options = { 
        host: 'localhost', 
        port: 4567, 
        path: '/', 
        method: 'POST' 
       }; 

var myFirstJSON = { "payload" : { "headers" : 
              [{ "from" : from, 
               "to" : to, 
               "subject" : subject }], 
           "body" : 
              [{ "primeira_parte" : primeira_parte, 
               "segunda_parte" : segunda_parte, 
               "terceira_parte": terceira_parte }] 
           }}; 
      req.write(JSON.stringify(myFirstJSON)); 

不過,我得到這個錯誤:

TypeError - can't convert nil into String: 


{"{\"payload\":{\"headers\":"=>{"{\"from\":\"[email protected]\",\"to\":\"[email protected]\",\"subject\":\"Testing\"}"=>{",\"body\":"=>{"{\"primeira_parte\":\"The following message to <[email protected]> was undeliverable.\\r\\nThe reason for the problem:\\r\\n5.1.0 - Unknown address error 553-'sorry, this recipient is not in my valid"=>"\\r\\nrcptto list (#5.7.1)'\",\"segunda_parte\":\"Final-Recipient: rfc822"}}}, "[email protected]\\r\\nAction: failed\\r\\nStatus: 5.0.0 (permanent failure)\\r\\nRemote-MTA: dns"=>nil, "216.75.35.163"=>{"\\r\\nDiagnostic-Code: smtp"=>nil}, "5.1.0 - Unknown address error 553-'sorry, this recipient is not in my validrcptto list (#5.7.1)' (delivery attempts: 0)\",\"terceira_parte\":\"Received: from unknown (HELO aws-bacon-delivery-svc-iad-1020.vdc.amazon.com) ("=>{"10.144.21.123"=>{")\\r\\n by na-mm-outgoing-6102-bacon.iad6.amazon.com with ESMTP"=>nil}}, "16 Apr 2011 14:11:15 0000\\r\\nReturn-Path: [email protected]il-bounces.amazonses.com\\r\\nDate: Sat, 16 Apr 2011 14:23:20 0000\\r\\nFrom: [email protected]\\r\\nTo: [email protected]\\r\\nMessage-ID: <[email protected]il.amazonses.com>\\r\\nSubject: Testing\\r\\nMime-Version: 1.0\\r\\nContent-Type: text/plain"=>nil, "\\r\\n charset"=>"UTF-8\\r\\nContent-Transfer-Encoding: 7bit\\r\\nX-AWS-Outgoing: 199.255.192.79\\r\\n\\r\\n<html><body><p> Helllooo </p></body></html>\\r\\n\\r\\n\"}]}}"} 
+0

你可以顯示你得到的東西puts params.inspect – 2011-04-17 14:47:12

+0

當然,我已經編輯了quesiton。 – donald 2011-04-17 14:53:08

回答

5

你想要的是像這樣的路線:

post '/' do 
    push = JSON.parse(request.body.read) 
    "I got JSON: #{push.inspect}" 
end 

你不是編碼的d ata,因此它不會被設置爲params。

+0

當我收到JSON對象時得到這個:127.0.0.1 - - [17/Apr/2011 15:57:08]「POST/HTTP/1.1」200 1371 0.0020 practivate.adobe.com - - [17/Apr/2011:15:57:08 WEST]「POST/HTTP/1.1」200 1371 - - >/ – donald 2011-04-17 14:57:28

+0

這很好,它表示請求成功。你回到你身上的是什麼更多的apropos問題?即,如果你打印出你從套接字中得到的響應,那包含了什麼?你期望什麼? – jer 2011-04-17 15:12:01

+0

是的,你是對的。謝謝。你能解釋爲什麼我的第一個代碼錯了嗎?我仍然不明白。謝謝 – donald 2011-04-17 15:17:34