【问题标题】:How to transform POST body response to get the elements?如何转换 POST 正文响应以获取元素?
【发布时间】:2017-03-14 03:58:31
【问题描述】:

我正在 Elixir 中使用 HTTPoison 发出网络请求:

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}}

我是 Elixir 的新手,我的问题是我想从 response.body 获取 results 元素

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

我不确定如何在 Elixir 中将此字符串转换为数组/哈希或 stuple。我在 Enum 有,但它似乎不起作用

【问题讨论】:

    标签: elixir elixir-poison


    【解决方案1】:

    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
    

    【讨论】:

    • 非常感谢 Dogbert,在我重新启用 Poison 依赖项后。我认为 Elixir 很棒。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    相关资源
    最近更新 更多