Rendering a Dictionary In JSON

Hi All,

Just an update for any future people who run into a similar problem.

Turns out my first problem is I was trying to pass in a list of maps, when I actually just wanted a singular map to represent the dictionary.

The solution I finally worked on was to put logic in the view to enumerate through the map and call the render_one function for each of the values and create a new map with the value equal to the view result struct rather than the actual struct.

This looked like as follows

  def render("user_with_associations_and_conversations.json", %{
        user: user,
        associations: associations,
        individual_conversations: individual_conversations
      }) do
    individual_conversations =
      Enum.into(
        Enum.map(individual_conversations, fn {key, value} ->
          {key, render_one(value, ConversationView, "individual_conversation.json")}
        end),
        %{}
      )

    %{
      data: %{
        id: user.id,
        email: user.email,
        firstName: user.first_name,
        lastName: user.last_name,
        associations: render_many(associations, AssociationView, "association.json"),
        individual_conversations:
          individual_conversations
      }
    }
  end
3 Likes