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 ![]()
Phoenix.NotAcceptableError at GET /api/v1/users
Exception:
How to fix this issue?
Trending in Questions
Hello!
Suppose you are building workflow (order / task / payment) processing system with the following requirements:
Each workflow con...
New
I’m aware of 2 such projects, are there others?
git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
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
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
Hi,
we run different LLM models across a cluster, with each node loading a configurable subset. Model-specific queues let nodes consume ...
New
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
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
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
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
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
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself.
My main conc...
New
(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
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #ai
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #blog-post
- #ecto-query
- #elixirconf-us
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #elixirconf-eu
- #api
- #forms
- #security
- #hex










Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
PatNowak
My suggestion is to use dedicated
viewfor 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
NobbZ
When phoenix asks for media-type
"json", it actually wants to see the MIME-type"application/json", you either have to convince phoenix aboutapplication/vnd.api+jsonbeeing 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
You can add new mime types to the mime library: GitHub - elixir-plug/mime: A read-only and immutable MIME type module for Elixir · GitHub
swilliamrobert
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
Just transform it in your controller. Do you have a specific example with code that is not working for you?
swilliamrobert
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
The name of what though? I’m not sure what you are trying to do…?
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
and use the view with
Then, in the corresponding view/action, You can customize your json output…
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
Thanks for your reply. I have updated the code and getting an error.
ArgumentError at GET /api/v1/users
Exception:
The user view file:
defmodule VampDev.UserView do
use VampDev.Web, :view
end
User controller file
web/models.user_controller.ex
defmodule VampDev.UserController do
use VampDev.Web, :controller
def index(conn, _params) do
end
How to fix this issue?
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.