【问题标题】:Encoding json using poison with unicode使用毒药和 unicode 对 json 进行编码
【发布时间】:2016-11-03 11:37:45
【问题描述】:

我正在使用 HTTPoison 获取 elixir 指南网站,然后使用 Floki 对其进行解析以构建 HTML 2 Jupyter Notebook 转换器(使用 Markdown 进行描述)。我必须输入`反引号。 \u0060 用于代码突出显示,到目前为止有效。我有一些地方使用字符串插值"#{Floki.text(childs_nodes)}" 和其他地方Enum.join "" 来处理和从HTML 转换为Markdown。

转换后的结果按照 jupyter notebook 格式存储在地图中。当我调用Poison.encode notebook 时,我收到一个错误,因为代码点已经消失。我尝试了不同的方法,但还不知道问题出在哪里。

任何提示我在处理文本时做错了什么?这是一个例外:

** (Poison.EncodeError) unable to encode value: {:source, ["Elixir also    provides `Port`, `Reference` and `PID` as data types (usually used in process communication), and we will take a quick look at them when talking about processes. For now, let’s take a look at some of the basic operators that go with our basic types."]}
lib/poison/encoder.ex:377: Poison.Encoder.Any.encode/2
lib/poison/encoder.ex:255: anonymous fn/3 in Poison.Encoder.List.encode/3
lib/poison/encoder.ex:256: Poison.Encoder.List."-encode/3-lists^foldr/2-1-"/3
lib/poison/encoder.ex:256: Poison.Encoder.List.encode/3
lib/poison.ex:41: Poison.encode!/2
(guide2nb) lib/cli.ex:27: CLI.process/1
(elixir) lib/kernel/cli.ex:76: anonymous fn/3 in Kernel.CLI.exec_fun/2

【问题讨论】:

  • 您尝试编码的值看起来不像地图,而是元组。在此处粘贴您的原始值(和/或尝试对其进行编码的代码)
  • Poison 不编码元组。

标签: elixir elixir-poison


【解决方案1】:

这里的问题是您尝试编码 Tuple,而 Poison 仅适用于 Maps 和 Lists。 如果您尝试编码的值是 Map 而不是元组,它会完美地工作。 Unicode 与此无关。

iex(1)> value = %{source: ["Elixir also    provides `Port`, `Reference` and `PID` as data types (usually used in process communication), and we will take a quick look at them when talking about processes. For now, let’s take a look at some of the basic operators that go with our basic types."]}
iex(2)> Poison.encode(value)
{:ok,
 "{\"source\":[\"Elixir also    provides `Port`, `Reference` and `PID` as data types (usually used in process communication), and we will take a quick look at them when talking about processes. For now, let’s take a look at some of the basic operators that go with our basic types.\"]}"}

【讨论】:

  • 感谢您的提示...我将重构我的代码。其实我只是使用地图和列表,但我在解析 HTML 树的递归中有一些 flat_maps。所以我的一些地图%{cell_type: :code, metadata: %{}, source: ["0o777"]}, 被转换为带有元组的关键字列表。 [{:cell_type, :markdown}, {:metadata, %{}}, {:source, ["# Basic types"]}, {:cell_type, :markdown}, {:metadata, %{}}, {:source, []},
  • 更改问题的名称以更准确地表示问题所在可能很有用。这会让其他人更容易参考。
猜你喜欢
  • 2017-09-19
  • 1970-01-01
  • 2017-08-07
  • 2017-10-27
  • 1970-01-01
  • 2011-09-18
  • 2017-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多