如何在 Elixir 中获取 JSON 属性 的值

How to get the value of a JSON property in Elixir

我正在将这种 os 数据返回给一个变量:

{"numbers":[0.8832325122263557,0.9905363563950811, ...]}

我怎样才能删除这个字符串“numbers”:并只使用 []?

这是一个脚本

  1. 使用 Mix.install/2 to instal Jason。在混合项目中,您可以将 jason 添加到 mix.exs 中的部门。
  2. 使用 ~S sigil 引用 JSON 而无需转义 " 字符。
  3. 使用Jason.decode!/2解析JSON。
  4. 使用 Map.get/3 从生成的映射中获取 numbers 键的值。
  5. 使用 IO.inspect/2 检查值,使其打印出来。
  6. 使用|> pipes在函数调用之间简洁地传递数据。
Mix.install([:jason])

~S({"numbers":[0.8832325122263557,0.9905363563950811]})
|> Jason.decode!()
|> Map.get("numbers")
|> IO.inspect()

运行 并输出:

$ elixir example.exs
[0.8832325122263557, 0.9905363563950811]

只是为了提出一个没有 JSON 解析器的替代解决方案,我会使用 Regex.

  1. 捕获括号内的任何字符串,例如[numbers]
  2. ,
  3. 拆分字符串
  4. 将字符串数字转换为浮点数
string = ~S({"numbers":[0.8832325122263557,0.9905363563950811]})

~r/(?:.+\[)(?'numbers'.+)(?:\].+)/
|> Regex.scan(string, capture: ["numbers"])
|> List.first()
|> List.first()
|> String.split(",")
|> Enum.map(&String.to_float/1)

如果您的输入总是像 {"numbers":[0.8832325122263557,0.9905363563950811, ...]}

,则此方法效果很好