Sebb

Sebb

Tuple keys to json

In Jason/Poison it is possibe to encode tuple values using

defimpl Encoder, for: Tuple do
  def encode(data, options) when is_tuple(data) do
    data
    |> Tuple.to_list()
    |> Encoder.List.encode(options)
  end
end

But it seems like there is no way no encode maps with tuple keys … right?

EDIT: As possible for values I’m looking for a way to explicitly transform the tuples to a valid json key (a string). For example sth like

defimpl EncoderThatAlsoHandlesKeys, for: Tuple do
  def encode(data, options) when is_tuple(data) do
    inspect(data)
   end
end

which hypothetically would transform:

%{{1,2} => "test"}

to

{"{1,2}": "test"}

Marked As Solved

Sebb

Sebb

Thanks for the insights guys. conclusion:

  • its not possible to hook into encoding of the keys
  • if you really want to, do it manually
  • or: flatten the maps, eg %{{1, 2} => %{...} becomes [%{key_: [1, 2], ...}, ...]
  • for the task I originally had (looking at data) use inspect(data, pretty: true, limit: infinity)
  • store data to reuse later in erlang world: use :erlang.term_to_binary and :erlang.binary_to_term
  • in general: JSON - there is some troube under the hood

Also Liked

LostKobrakai

LostKobrakai

That’s a more long form explanation to that approach.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

The way that I’d do this is with an actually explicit transformation. As in, instead of map_with_tuple_keys |> Jason.encode! do map_with_tuple_keys |> keys_to_strings |> Jason.encode! where keys_to_strings/1 goes through and explicitly turns all of your tuple keys into a string of your choosing.

Qqwy

Qqwy

TypeCheck Core Team

I like the approach @benwilson512 shared.
If you want to explicitly encode your map keys, call a function on your map to turn them into strings before calling Jason.encode! or another encoding function.

You could encode those tuples using inspect().

If you want to be able to decode datatypes later, then inspect cannot help you however: Turning them back into Elixir requires calling Code.eval_string (which is a function of last resort), and will not be able to deal with opaque datatypes like MapSet, Stream, etc. that return an inspect format which starts with a # (as this is read as a comment).

Another approach is using :erlang.term_to_binary (and :erlang.binary_to_term to decode). This supports (with very few exceptions) all datatypes of Elixir/Erlang, and encoding/decoding is quite performant.
Libraries for some other languages besides the BEAM exist as well.
However, this is a binary format and thus it is not humanly readable.

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
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

We're in Beta

About us Mission Statement