riccardomanfrin
I wrote a sample module that overrides Jason.Encoder.encode protocol for Map.
defmodule JsonEncoder do
defimpl Jason.Encoder, for: Map do
def encode(value, opts) do
IO.inspect(PASSINGHERE)
value
|> Enum.filter(fn {k, _v} -> k != :c end)
|> Jason.Encode.keyword(opts)
end
end
#test call
def enc() do
%{a: 1, b: 2, c: 3} |> Jason.encode!()
end
end
While doing the same for a custom struct was working, when I do it for generic Map type, it doesn’t.
I can see the compiler detects the redefinition:
iex(8)> recompile
Compiling 1 file (.ex)
warning: redefining module Jason.Encoder.Map (current version loaded from _build/dev/lib/jason/ebin/Elixir.Jason.Encoder.Map.beam)
│
2 │ defimpl Jason.Encoder, for: Map do
│ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
│
└─ test/support/json_encoder.ex:2: Jason.Encoder.Map (module)
Generated sampleapp app
:ok
but when I run the test call, I don’t see my code to be triggered.
iex(9)> JsonSortedEncoder.enc
"{\"c\":3,\"a\":1,\"b\":2}"
iex(10)>
What am I missing?
Thanks in advance
Trending in Questions
Hey guys,
I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly
Do you guys have any suggestions what is the best prac...
New
Hello!
Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app.
I creat...
New
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
Hello,
I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter).
The diffic...
New
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
Anyone here using Honeybadger?
My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of
Bandit.HTTPError...
New
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
Other Trending Topics
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
There are three potential reasons for members of this forum to have a look at https://vutuv.de
You are tired or annoyed of LinkedIn.
Yo...
New
Aludel - LLM Evaluation Workbench
Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixir-ls
- #ai
- #elixirconf-us
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 4- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
LostKobrakai
Overriding protocol implementations is afaik not something elixir wants you to do. I’d stay away from that.
Jason has Jason.OrderedObject — jason v1.5.0-alpha.2 for your usecase.
arcanemachine
I was never able to get OrderedObject figured out (and nobody’s ever chimed in with an example), so here’s a homebrewed version of how I sort my encoded maps:
Note that this would have to be done on a struct-by-struct basis.
riccardomanfrin
I as well didn’t very well understand the OrderedObject thing. Or at least I didn’t find it could fit my case.
Let me define the usecase a bit better (and by the way I managed to circumnvent the sorting problem by deserializing the json back into a map at later stage, so this has become more of a general question on why
defimplisn’t doing the job rather than an actual problem).Suppose I have a tree of maps nested one within each others ad unknown depths:
The
Jason.Encoderis taking care of the recursion through theMaptypes already, so I wanted to exploit it to do other side jobs (e.g. maybe removing a particular key when found in the maps - also in the maps nested within -).The solution you kindly offered requires me to first iterate the maps to make them into the
__MODULE__struct, which sort of defeats the purpuse (right?)LostKobrakai
The usecases of
Jason.OrderedObjectare kinda twofold. The primary usecase is allowing minimal modifications to existing json strings. That includes not arbitrarily reordering object keys. So on decoding you can add an option so objects are decoded as ordered_objects, so they can be encoded back into the same order, while allowing modification between.You can however also use
Jason.OrderedObjectto create ordered objects if you’re dealing with a consumer, which for whatever reason depends on order in objects even though they shouldn’t.Given the choice of words I guess you’re already aware that this is not necessarily a great idea. Protocols are globally registered. Using it for none general behaviour will be bad for the next person, who doesn’t need your side jobs to apply – requiring them to add even more hacky overrides over your hacky overrides to get rid of them. If you want to go that route I’d strongly suggest using elixirs
JSONif you can. It allows adjusting how data is encoded as a function parameter, which can compose multiple behaviours better than just relying on protocols.