mcintyre1994

mcintyre1994

If I have a struct (with maybe some nested structs), and it has atom keys, what’s the most idiomatic way to get from user input in the form of a JSON request body to that struct? In my day job I use Scala + Play Framework and this is really easy to do, but I think in Elixir I’m getting caught up on the fact that user input → atom is a DoS vector.

So Phoenix presents my JSON body to my controller function in conn.body_params, nicely parsed into a map - with string keys. I can’t parse this to a struct using Kernel.struct because the string keys are ignored - and I can’t convert them to atoms without a potential DoS.

The only thing I can think of that would probably work is converting that map back into JSON, and then decoding it using Poison’s as parameter. But that seems really wasteful because Plug already converted it from JSON → map, then I’m doing map → JSON → struct.

I guess I’m wondering if there’s anything more idiomatic/automated/safe than just doing something like this in the controller:

body_params = conn.body_params

user = %User{
  name: body_params["name"],
  age: body_params["age"],
  occupation: %Occupation{
    job_title: body_params["occupation"]["job_title"]
  }
}

Which seems quite error prone and tedious particularly where there’s a lot of nesting, JSON lists, etc.

Showing Posts 1 to 10

kokolegorille

kokolegorille

Converting data from the outside is usually done with changesets in Elixir, with or without database.

Something like

{:ok, user} = %User{}
|> User.changeset(body_params)
|> Ecto.Changeset.apply_action(:insert)
12
Post #1
sztosz

sztosz

Structs are actually just maps with a additional key __struct__, so %User{a: 1} is simply a map %{__struct__: User, a: 1} underneath. You can hack the map you have, by converting keys from strings to atoms, and then adding the proper __struct__ key.

Or maybe just simply use struct function, here are examples: Kernel — Elixir v1.20.2 but you will have to convert keys from that map to atoms, and then that map to keyword list.

From my experience, it’s just easier and more readable, when you have specialized functions in your module that declares that struct. and invoke them whenever you have need to create that struct from params map, You can add there proper validation etc with Ecto embeded schemas etc.

mcintyre1994

mcintyre1994 OP

Thanks - I had left Ecto out when I started the Phoenix app because I’m not using a database but it looks like changeset is still the best approach here.

daskycodes

daskycodes

If you are still thinking about going completely without ecto you could try something like this

defmodule StructMap.User do
  defstruct [:name, :age]

  def map_to_struct(map) do
    #convert string keys to atoms
    map = Map.new(map, fn {k, v} -> {String.to_atom(k), v} end)

    # return struct from map
    struct(__MODULE__, map)
  end
end

iex(1)> StructMap.User.map_to_struct(%{"name" => "mike", "age" => 12})
%StructMap.User{age: 12, name: "mike"}
kokolegorille

kokolegorille

Hello and welcome,

This could lead to potential :atom overflow,

daskycodes

daskycodes

Hello and thank you,

Thank you for mentioning :atom overflow I haven’t thought about that. Atoms are not garbage-collected.

ityonemo

ityonemo

I think half the elixir community is waiting for the ecto team to break off changesets like Phoenix did with pubsub.

kokolegorille

kokolegorille

Spliting ecto and ecto_sql was already nice :slight_smile:

fxn

fxn

Nice thing about changesets is that you can still define an embedded schema and get casts and validations.

LostKobrakai

LostKobrakai

One doesn’t even need schemas. There are schemaless changesets.

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews