2017-03-13 64 views
1

我在製作藥劑使用HTTPoison web請求:如何轉換POST body響應以獲取元素?

HTTPpoison.post "http://localhost:3000/mymodels"," {\"param1\": \"#{value1}\" , \"param2\":\"#{value2}\"} ", [{"Content-Type", "application/json"}] 

這是我得到的迴應:

{:ok, 
%HTTPoison.Response{body: "{\"id\":46,\"result\":18,\"param1\":\"liqueur\",\"param2\":\"quif\"}", 
    headers: [{"X-Frame-Options", "SAMEORIGIN"}, 
    {"X-XSS-Protection", "1; mode=block"}, {"X-Content-Type-Options", "nosniff"}, 
    {"Location", "http://localhost:3000/mymodels/46"}, 
    {"Content-Type", "application/json; charset=utf-8"}, 
    {"ETag", "W/\"05b8c75e0a5288c835651f48d4b8a80a\""}, 
    {"Cache-Control", "max-age=0, private, must-revalidate"}, 
    {"X-Request-Id", "1e8ae2d3-073a-4779-916a-edffc38f8b5a"}, 
    {"X-Runtime", "0.530440"}, {"Transfer-Encoding", "chunked"}], 
    status_code: 201}} 

我是新來的靈藥,我的問題是我想要得到的resultsresponse.body

iex(3)> response.body   
"{\"id\":46,\"results\":18,\"param1\":\"liqueur\",\"param2\":\"quif\"}" 

元素我不知道如何將這個字符串轉換成數組/哈希或stuple在Elixir。我在Enum,但它似乎並不工作

回答

6

response.body是一個JSON編碼的字符串。您需要先使用JSON解析器將其解析爲適當的Elixir數據結構。隨着Poison,你會使用Poison.decode!/1

iex(1)> body = "{\"id\":46,\"results\":18,\"param1\":\"liqueur\",\"param2\":\"quif\"}" 
"{\"id\":46,\"results\":18,\"param1\":\"liqueur\",\"param2\":\"quif\"}" 
iex(2)> json = Poison.decode!(body) 
%{"id" => 46, "param1" => "liqueur", "param2" => "quif", "results" => 18} 
iex(3)> json["results"] 
18 
+0

十分感謝Dogbert,把毒藥依賴後,我又回到了。我認爲藥劑很棒。 – FredyK

相關問題