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.

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
Gee-Bee

Gee-Bee

As of Jason version 1.2.0 decode/2 now supports keys option.

It’s worth to mention though it can lead to DoS attack when json data is user controlled.

moogle19

moogle19

Quick question: Why not use Ecto.Enum for the job and {:array, Ecto.Enum} for the hobbies?

Where Next?

Popular in Questions Top

yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
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

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
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
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New

We're in Beta

About us Mission Statement