stefanchrobot

stefanchrobot

How to decode a JSON into a struct safely?

What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with string keys, but struct() expects atom keys.

First Post!

paulsullivanjr

paulsullivanjr

Is using Poison an option?

Most Liked

LostKobrakai

LostKobrakai

Map.new(%Foo{}, fn {key, _} -> {key, json[Atom.to_string(key)]} end)
joefractal

joefractal

Quick example

defmodule Foo do
  @derive [Poison.Encoder]
  defstruct [:bar]
end

defmodule Example do
  def test do
    s = "{\"bar\":\"baz\"}"
    Poison.decode!(s, as: %Foo{})
  end
end

iex(1)> Example.test
%Foo{bar: “baz”}

There are probably more modern ways to do it, but this is was I have been using. You can also nest structs this way.

The number of json encode/decoders seems to grow everyday. https://package-rank.com/wp/hex/poison/-vs-/hex/jason

axelson

axelson

Scenic Core Team

You can also always decode manually and completely explicitly. It is more typing but it also allows you to change the struct or the parameters independently. It is not always the best way but sometimes is.

defmodule Foo do
  defstruct [:bar, :baz]
end

defmodule Example do
  def test do
    s = '{"bar":"abc", "baz": 42}'
    json = Poison.decode!(s)
    %Foo{
      bar: json["bar"],
      baz: json["baz"],
    }
  end
end

Last Post!

agreif

agreif

thanks!

Where Next?

Popular in Questions Top

vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New

Other popular topics Top

electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 40165 209
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

We're in Beta

About us Mission Statement