shahryarjb

shahryarjb

How to convert multi struct in a list to Json in phoenix controller

Hello, I have a struct that was made with preload, this output cannot be converted to json encode.
it should be noted, I can’t use @derive in my schema files, but I use it in my query file, but the task was broken , because I have multi struct in a list.

now how can I convert it to json, I’m using Jason lib,

my preload:

def show_support_with_code(code, user_id) do
      query = from u in SupportSchema,
          where: u.code == ^code,
          join: a in assoc(u, :users),
          # where: a.id == ^user_id,
          left_join: b in assoc(u, :blog_posts),
          left_join: c in assoc(u, :support_replies),
          left_join: d in assoc(c, :users),
          order_by: [desc: c.inserted_at],
          preload: [users: a, blog_posts: b, support_replies: {c, users: d}]
      
      case Repo.one(query) do
         nil -> {:error, :show_support_with_code}
         info -> {:ok, :show_support_with_code, info}
      end
    end

output preload:

%BankError.ClientApi.Support.SupportSchema{
   __meta__: #Ecto.Schema.Metadata<:loaded, "supports">,
   blog_posts: nil,
   code: "test47",
   description: "بررسی بهینه سازی در اگهی",
   id: "cd33f63f-44c5-46a7-848c-8926be21dd82",
   inserted_at: ~N[2019-08-25 17:43:49],
   post_id: nil,
   status: 3,
   support_replies: [
     %BankError.Support.SupportReplySchema{
       __meta__: #Ecto.Schema.Metadata<:loaded, "support_replies">,
       description: "برای تست اینجاییم",
       id: "e67dae2f-237c-439f-bee7-846f8f575cc9",
       inserted_at: ~N[2019-08-29 17:24:25],
       status: true,
       support_id: "cd33f63f-44c5-46a7-848c-8926be21dd82",
       supports: #Ecto.Association.NotLoaded<association :supports is not loaded>,
       updated_at: ~N[2019-08-29 17:24:26],
       user_id: "40c06a6b-15a0-4888-999b-132fbd326455",
       users: %BankError.Users.UserSchema{
         __meta__: #Ecto.Schema.Metadata<:loaded, "users">,
         id: "40c06a6b-15a0-4888-999b-132fbd326455",
         inserted_at: ~N[2019-05-26 08:12:14],
         last_name: "soam",
         mobile: "09213780329",
         name: "shiam",
         password: nil,
         password_hash: "$2b$12$N2c6fKCVez7ZB/5k7coXkuwNaVGESQboFNba8cmRcRqoaKufs4PAC",
         role: 1,
         status: 1,
         support_replies: #Ecto.Association.NotLoaded<association :support_replies is not loaded>,
         supports: #Ecto.Association.NotLoaded<association :supports is not loaded>,
         transactions: #Ecto.Association.NotLoaded<association :transactions is not loaded>,
         updated_at: ~N[2019-05-26 08:12:14]
       }
     }
   ],
   title: "ساختمان سازی یک تست دوم",
   type: "other",
   updated_at: ~N[2019-08-26 06:29:23],
   user_id: "d0c1c8c5-6747-47c7-ba21-89a15017be3c",
   users: %BankError.Users.UserSchema{
     __meta__: #Ecto.Schema.Metadata<:loaded, "users">,
     id: "d0c1c8c5-6747-47c7-ba21-89a15017be3c",
     inserted_at: ~N[2019-04-16 08:20:10],
     last_name: "tavakkoli",
     mobile: "09368094936",
     name: "shahryar",
     password: nil,
     password_hash: "$2b$12$k/Ql7o9VyUbeeHi3Dr1BuOub2Wdg6NZ0I8bIfM8SmaqNop8o60H.G",
     role: 3,
     status: 2,
     support_replies: #Ecto.Association.NotLoaded<association :support_replies is not loaded>,
     supports: #Ecto.Association.NotLoaded<association :supports is not loaded>,
     transactions: #Ecto.Association.NotLoaded<association :transactions is not loaded>,
     updated_at: ~N[2019-08-26 05:38:18]
   }
 }

Marked As Solved

shahryarjb

shahryarjb

Hello again, I made some progress

I added this line in my controller (BankErrorWeb.ApiSupportController):

require Protocol
Protocol.derive(Jason.Encoder, BankError.ClientApi.Support.SupportSchema, only: [:title, :description, :type, :status, :code, :users, :blog_posts])

after adding top line code in my controller I added @derive {Jason.Encoder, only: [..]} into my schema files that were connected like, (users, blog_posts, support_replies)

it works but it has a problem, because I don’t input support_replies: {c, users: d} in my preload, I mean

Protocol.derive(Jason.Encoder, BankError.ClientApi.Support.SupportSchema, only: [:title, :description, :type, :status, :code, :users, :blog_posts, :support_replies])

if support_replies added !!! :frowning_face: it shows me this error:

** (exit) an exception was raised:
    ** (Protocol.UndefinedError) protocol Jason.Encoder not implemented for %BankError.Support.SupportReplySchema{__meta__: #Ecto.Schema.Metadata<:loaded, "support_replies">
   def show_support_with_code(code, user_id) do
     query = from u in SupportSchema,
         where: u.code == ^code,
         join: a in assoc(u, :users),
         where: a.id == ^user_id,
         left_join: b in assoc(u, :blog_posts),
         left_join: c in assoc(u, :support_replies),
         left_join: d in assoc(c, :users),
         order_by: [desc: c.inserted_at],
         preload: [users: a, blog_posts: b, support_replies: {c, users: d}]
     
     case Repo.one(query) do
        nil -> {:error, :show_support_with_code}
        info -> {:ok, :show_support_with_code, info}
     end
   end

update

it is fixed, I had a bad schema relation

Thanks

Also Liked

albydarned

albydarned

Have you tried a simple

Map.from_struct

shahryarjb

shahryarjb

I tested it

   def test1() do
      [
         %BankError.Support.SupportReplySchema{
           __meta__: "s",
           description: "برای تست اینجاییم",
           id: "e67dae2f-237c-439f-bee7-846f8f575cc9",
           inserted_at: ~N[2019-08-29 17:24:25],
           status: true,
           support_id: "cd33f63f-44c5-46a7-848c-8926be21dd82",
           supports: "#Ecto.Association.NotLoaded<association :supports is not loaded>",
           updated_at: ~N[2019-08-29 17:24:26],
           user_id: "40c06a6b-15a0-4888-999b-132fbd326455",
           users: %BankError.Users.UserSchema{
             __meta__: "",
             id: "40c06a6b-15a0-4888-999b-132fbd326455",
             inserted_at: ~N[2019-05-26 08:12:14],
             last_name: "soam",
             mobile: "09213780329",
             name: "shiam",
             password: nil,
             password_hash: "$2b$12$N2c6fKCVez7ZB/5k7coXkuwNaVGESQboFNba8cmRcRqoaKufs4PAC",
             role: 1,
             status: 1,
             support_replies: "#Ecto.Association.NotLoaded<association :support_replies is not loaded>",
             supports: "#Ecto.Association.NotLoaded<association :supports is not loaded>",
             transactions: "#Ecto.Association.NotLoaded<association :transactions is not loaded>",
             updated_at: ~N[2019-05-26 08:12:14]
           }
         }
       ]
       |> test
   end
   def test(struct) do
      struct
      |> Enum.map(fn %{users: users} = x -> 
         x
         |> Map.delete(:__struct__) # change the struct to a Map
         |> Map.drop([:__meta__])
         |> Enum.filter(fn {c, v} -> v end)
         |> Enum.into(%{})
      end)   
   end

but the output is:

I can’t be able to delete %BankError.Users.UserSchema and some field like __meta__ and etc in users map

help me please

@peerreynders @OvermindDL1 @NobbZ

albydarned

albydarned

I can’t use @derive in my schema files

Why?

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

Other popular topics Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement