Skip to content

Instantly share code, notes, and snippets.

@desmondhume
Created August 6, 2016 18:13
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save desmondhume/0fcb73bf6b7f4d9ed267d1c99c96471d to your computer and use it in GitHub Desktop.
Save desmondhume/0fcb73bf6b7f4d9ed267d1c99c96471d to your computer and use it in GitHub Desktop.
Convert elixir map to query string
defmodule URL do
def to_query(input, namespace) do
Enum.map(input, fn({key, value}) -> parse("#{namespace}[#{key}]",value)end)
|> Enum.join("&")
end
def to_query(input) do
Enum.map(input, fn({key, value}) -> parse(key,value) end)
|> Enum.join("&")
end
def parse(key, value) when is_map(value) do
to_query(value, key)
end
def parse(key, value) do:
"#{key}=#{value}"
end
end
@nathanhornby
Copy link

nathanhornby commented Apr 12, 2017

Came here looking for a more elegant solution to what I felt wasn't very 'functional'.

@endpoint "https://domain.tld"
options_list = Map.to_list(options)
options_formatted = ""

for {key, value} <- options_list do
  options_formatted <> "?" <> Atom.to_string(key) <> "=" <> value <> "&"
end

@endpoint <> options_formatted

The to_query function is especially neat! Thanks for the inspiration.

@nathanl
Copy link

nathanl commented Sep 26, 2017

I think https://hexdocs.pm/elixir/URI.html#encode_query/1 would be the first thing to try

@ltfschoen
Copy link

ltfschoen commented Jan 28, 2018

Convert Query String Parameters into a Map of Key/Value Pairs:

iex(29)> String.split("from=ME&to=YOU&to_index=THERE&proof=PROVEN", ~r/&|=/) |> Enum.chunk(2) |> Map.new(fn [k, v] -> {k, v} end)
%{"from" => "ME", "proof" => "PROVEN", "to" => "YOU", "to_index" => "THERE"}

https://gist.github.com/ltfschoen/a52109ea5a9e020fa4abcaacbc43e8af

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment