JSON API in Phoenix

This might be a stupid question but I’m struggling with getting my head around working with views while I’m learning Elixir.

I have a model that uses an embedded schema along the lines of:

defmodule Actions do
  embedded_schema do
    field :method, :string
    field :value, :string

With method essentially being an enum of action types eg log, modify etc. the goal being to use method as the key for the pair.

With eex it’s simple to pass to the template and display whatever way I want. But how would I go generating a JSON response structured like:

"actions": { "log": "foobar" }

Thanks in advance.


I don’t think it’s more complicated to render json than rendering template…

Could You please show this template?

Also, it’s not really clear about actions

"actions": { "log": "foobar" }

with plural, it’s probably a collection, and not a single element.

"actions": [{ "log": "foobar" }]

Maybe something like this pseudo code?

  def render("index.json", %{actions: actions}) do
    %{data: render_many(actions, ActionView, "action.json")}

  def render("action.json", %{action: action}) do
    %{action.method => action.value}

Thanks for your help. I think I need to spend more time rtfm.

Another silly newbie question, sorry.

Playing about trying to understand how to render different structures, I hit a wall trying to turn this into an nested array e.g.

"actions": [[ "log","foobar" ]]

I had thought to_list would have done it but apparently not.

def render("action.json", %{action: action}) do
  Map.to_list(%{action.method => action.value})

Keep it simple :slight_smile:

  def render("action.json", %{action: action}) do
    [action.method, action.value]

Although I prefer to have a list of struct rather than a list of list


Thank you for your time and patience :+1::+1::+1: