简体   繁体   English

长生不老药毒液无法解码JSON

[英]elixir poison not able to decode JSON

I am trying below code 我正在尝试下面的代码

data = Poison.decode!(payload)
    |> ProperCase.to_snake_case
Logger.info("data is #{data}")

Where the payload is from Messging Queue 有效负载来自Messging Queue

    {
      "name":"Joe",
      "id": "13",
      "version": 0
    }

With this I am getting an error 有了这个我得到一个错误

[error] Could not process PerfectFlight: %Protocol.UndefinedError{description: "", protocol: String.Chars, value: %{"id" => "13", "name" => "Joe", "version" => 0}}

However, If I change my input json to 但是,如果我将输入json更改为

 "{
  \"name\":\"Joe\",
  \"id\": \"13\",
  \"version\": 0
}"

The Poison.decode() works pefectly fine. Poison.decode()可以很好地工作。 Now the issue is that I don't want to change my input JSON because of many reasons. 现在的问题是,由于多种原因,我不想更改输入的JSON What am I missing? 我想念什么?

Edit : The code was failing not at the decode but on the next line Logger.info("data is #{data}") . 编辑 :该代码不是在解码时失败,而是在下一行Logger.info("data is #{data}")处失败。 Since the output of decode function is not a String I should rather use IO.inspect as below. 由于decode功能的输出不是String我应该使用IO.inspect如下。 Accepting Adams answer for his confidence in decode function. 接受Adams的回答是因为他对解码功能充满信心。

data = Poison.decode!(payload)
    |> ProperCase.to_snake_case
IO.inspect(data)

There is nothing wrong with Poison: 毒药没有错:

iex(1)> Poison.decode!(~S'{"name":"Joe", "id": "13", "version": 0}')
%{"id" => "13", "name" => "Joe", "version" => 0}

Your example also works for me: 您的示例也适用于我:

iex(1)> payload = ~S'{"name":"Joe", "id": "13", "version": 0}'
"{\"name\":\"Joe\", \"id\": \"13\", \"version\": 0}"
iex(2)> Poison.decode!(payload) |> ProperCase.to_snake_case
%{"id" => "13", "name" => "Joe", "version" => 0}

The error you are getting is probably because something somewhere is trying to convert a map to a string: 您收到的错误可能是因为某处某处正在尝试将映射转换为字符串:

iex(1)> IO.puts %{"id" => "13", "name" => "Joe", "version" => 0}
** (Protocol.UndefinedError) protocol String.Chars not implemented for %{"id" => "13", "name" => "Joe", "version" => 0}

It looks like you're getting an error while trying to debug your problem. 您似乎在尝试调试问题时遇到错误。 You could use IO.inspect instead of IO.puts for debugging, and see if you can get a more helpful error message. 您可以使用IO.inspect而不是IO.puts进行调试,并查看是否可以获得更有用的错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM