Sardoan
Change keyword list to map for json encoding
Hi,
I have this structure:
[%{"next" => "http://www.example.com/test?foo=bar&page=4"},
%{"prev" => "http://www.example.com/test?foo=bar&page=2"},
%{"first" => "http://www.example.com/test?foo=bar&page=1"},
%{"last" => "http://www.example.com/test?foo=bar&page=5"}]
With Poison.encode! I get following:
"[{\"next\":\"http://www.example.com/test?foo=bar&page=4\"},
{\"prev\":\"http://www.example.com/test?foo=bar&page=2\"},
{\"first\":\"http://www.example.com/test?foo=bar&page=1\"},
{\"last\":\"http://www.example.com/test?foo=bar&page=5\"}]"
After parsing in JS with JSON.parse I recieve an array with 4 fields. What I need is a simple struct without an array, so I can access it in JS via struct.next, sruct.prev …
How can I transform the keyword list to a struct, which gives me the JSON I need?
Any idea?
Most Liked
NobbZ
You can transform the list, as shown by @LostKobrakai, but you really should consider using a map on the elixir side from the beginning.
A list of maps, one key each feels wrong, especially when you say, that you consider this a single entity at the other end of the application.
LostKobrakai
For your example Enum.reduce(list, &Map.merge/2) should work, but I’d first consider why you’re having that list in the first place.
peerreynders
This was really the core issue because had they been tuples:
iex(1)> key_values = [
...(1)> {"next","http://www.example.com/test?foo=bar&page=4"},
...(1)> {"prev","http://www.example.com/test?foo=bar&page=2"},
...(1)> {"first","http://www.example.com/test?foo=bar&page=1"},
...(1)> {"last","http://www.example.com/test?foo=bar&page=5"}
...(1)> ]
[
{"next", "http://www.example.com/test?foo=bar&page=4"},
{"prev", "http://www.example.com/test?foo=bar&page=2"},
{"first", "http://www.example.com/test?foo=bar&page=1"},
{"last", "http://www.example.com/test?foo=bar&page=5"}
]
iex(2)> my_map = Map.new(key_values)
%{
"first" => "http://www.example.com/test?foo=bar&page=1",
"last" => "http://www.example.com/test?foo=bar&page=5",
"next" => "http://www.example.com/test?foo=bar&page=4",
"prev" => "http://www.example.com/test?foo=bar&page=2"
}
iex(3)>







