swilliamrobert

swilliamrobert

Hi, I need to create customize json format. I have used many to many relationships with user, tags and taggable. Please find the code below here.

User Controller

web/models.user_controller.ex

defmodule VampDev.UserController do
  use VampDev.Web, :controller

  def index(conn, _params) do
 
    user =
      VampDev.User
      |> Repo.all()
      |> Repo.preload(:tags)

    json(conn, %{user: user})
	  
	  end
end 

User model

web/models.user.ex

defmodule VampDev.User do
  use Ecto.Schema
  use VampDev.Web, :model
  
  @primary_key {:id, :string, []}
  schema "users" do
    field :name, :string
    field :country, :string
    many_to_many :tags, VampDev.Tag, join_through: "taggables"
  end
end

This is json output

// 20171107045356
// http://localhost:4000/api/v1/users

{
  "type": [
    {
      "tags": [
        {
          "name": "photo",
          "id": "a7d41c25-0452-47eb-b400-7237b2ff2c6d"
        }
      ],
      "name": "Alberto Giubilini",
      "id": "042807cc-26e1-4122-9235-23412eacaa79",
      "country": "Singapore"
    },
    {
      "tags": [
        {
          "name": "photo",
          "id": "a7d41c25-0452-47eb-b400-7237b2ff2c6d"
        }
      ],
      "name": "Hannah Maslen",
      "id": "0bdb2538-76c1-49b8-bee0-f27bbbfff8ae",
      "country": "Hong Kong"
    },
  ]
}

I have to customize the above json based upon the below Script .

JS in front end

<script>
    let request = (method, path) => {
      var headers = new Headers();
      headers.append('Accept', 'application/vnd.api+json');
      return fetch(new Request(`http://localhost:${path}`, {
        method,
        headers,
        mode: 'cors',
        cache: 'default'
      }));
    };
    let get = (path) => { return request('GET', path) };
    let put = (path) => { return request('PUT', path); };
    let post = (path) => { return request('POST', path); };
	
    (function init() {
     get('/vamp_test.php').then(response => {
        return response.json();
      }).then(json => {
        var includedMap = {};
        json.included.forEach(item => {
          if (!includedMap[item.type]) {
            includedMap[item.type] = {};
          }
          includedMap[item.type][item.id] = item;
        });

        json.data.forEach(item => {
          if (item.type && item.type.toLowerCase() === 'user' && item.relationships.taggables.data.length > 0) {
            var tagsHtml = item.relationships.taggables.data.map(taggableRelationship => {
              if (taggableRelationship && taggableRelationship.type === 'taggable') {
                var taggable = includedMap[taggableRelationship.type][taggableRelationship.id];
                if (taggable && taggable.relationships && taggable.relationships.tag && taggable.relationships.tag.data) {
                  var tag = includedMap[taggable.relationships.tag.data.type][taggable.relationships.tag.data.id];
                  if (tag) {
                    return `<span class="tag label label-default"">${tag.attributes.name}</span> `;
                  }
                }
              }
              return '';
            }).join('');

            var name = item.attributes['full-name'];
            var country = item.attributes.country || 'the earth';
            $("#main-list").append(`<li class="list-group-item"><span class="name"><strong>${name}</strong> from ${country}</span><div class="tags">${tagsHtml}</div></li>`);
          }
        })
      });
    })();
  </script>

I am getting the below error message whenever i run the page :frowning2:

Phoenix.NotAcceptableError at GET /api/v1/users

Exception:

How to fix this issue?

Showing Posts 1 to 10

PatNowak

PatNowak

My suggestion is to use dedicated view for rendering the JSON as you would like, which would, eventually, remove the need of using any external JS to render your data.

Btw this JS snippet is … weird. You want to do some requests to localhost and also get PHP page :slight_smile:

NobbZ

NobbZ

When phoenix asks for media-type "json", it actually wants to see the MIME-type "application/json", you either have to convince phoenix about application/vnd.api+json beeing an acceptable MIME-type (I’m not sure how if possible at all) or let your javascript issue with a correctly set accept header.

josevalim

josevalim

Creator of Elixir
swilliamrobert

swilliamrobert OP

Hi Thanks Josevalim. Do you have any idea to customize the JSON format in the user controller?
In the json format i wanted to change the ‘tags’ to ‘taggable’. Please advice me.

OvermindDL1

OvermindDL1

Just transform it in your controller. Do you have a specific example with code that is not working for you?

swilliamrobert

swilliamrobert OP

The api is working fine. But I just wanted to know how to change the name in the controller. If you have any example code, please provide.

OvermindDL1

OvermindDL1

The name of what though? I’m not sure what you are trying to do…?

kokolegorille

kokolegorille

To modify json output, You may want to look at Poison and @derive option. You can also implement your own poison encoder.

But to keep it simple, it is also possible not to use

json(conn, %{user: user})

and use the view with

conn |> render(“whatever.json”, user: user)

Then, in the corresponding view/action, You can customize your json output…

def render("whatever.json", %{user: user}), do: %{user: user_json(user)}

defp user_json(user), do: %{whatever_id: user.id, whatever_you_name: user.name, taggables: tags_json(user.tags)}

defp tags_json(tags) ... etc.

You can nest association, and use a custom to_json function for tags, where You can use taggables instead of tags.

UPDATE: I just noticed @PatNowak is advising the same use of custom view, some posts above, sorry for duplication

swilliamrobert

swilliamrobert OP

Thanks for your reply. I have updated the code and getting an error.

ArgumentError at GET /api/v1/users

Exception:

** (ArgumentError) argument error
    :erlang.apply([%VampDev.User{__meta__: #Ecto.Schema.Metadata<:loaded, "users">,

The user view file:
defmodule VampDev.UserView do
use VampDev.Web, :view

def render("index.json", %{user: user}) do
user_json(user)
end

defp user_json(user) do
%{id: user.id, name: user.name, taggables: tags_json(user.tags)}
end

defp tags_json(tags) do
%{id: tags.id, name: tags.name}
end

end

User controller file

web/models.user_controller.ex

defmodule VampDev.UserController do
use VampDev.Web, :controller

def index(conn, _params) do

user =
  VampDev.User
  |> Repo.all()
  |> Repo.preload(:tags)

  render conn, user: user
  
  end

end

How to fix this issue? :frowning:

kokolegorille

kokolegorille

I think tags is a collection, not an element…

You should have a defp tag_json for one tag element, and tags_json mapping through tags, returning a list.

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
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
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
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews