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
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
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
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
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
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
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
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
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
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
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
Hi everyone!
The first release candidate for the Expert language server project is now available!
We’ve published a press release detai...
New
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
Latest Phoenix Threads
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
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ai
- #ecto-query
- #elixirconf-us
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #elixirconf-eu
- #api
- #forms
- #metaprogramming
- #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.