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

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
water
I’m aware of 2 such projects, are there others? git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
itzmidinesh
Hi all, I’m working on a Phoenix project where I need to make external HTTP requests and I’m trying to choose between Req and HTTPoison....
New
peck
Hi everyone. My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
leoschweizer
Hi, we run different LLM models across a cluster, with each node loading a configurable subset. Model-specific queues let nodes consume ...
New
csmr
Hi all, I’m new here and would like to hear peoples views on my Elixir/Phoenix based game-engine! :smiley: Mutonex gamedesign was finish...
New
perzanko
Do we have maintainer of absinthe-graphql/dataloader here? We have a PR that we’d like to merge to the library. Relatively small additive...
New

Other Trending Topics Top

dominicletz
Hey there, I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first. ...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews