I am attempting to port the Golang tutorial geddit to Elixir. I have done so successfully with Dartlang, but Elixir's operations on maps & lists are confusing for me.
Using HTTPoison and JSEX, I have the following code:
defmodule Redditex do
use HTTPoison.Base
def process_url(url) do
"http://www.reddit.com/r/#{url}.json"
end
def process_response_body(body) do
json = JSEX.decode! body
json = Enum.map json, fn ({k, v}) -> {String.to_atom(k), v } end
json
end
end
My difficulty is parsing the JSON body into an appropriate struct where the JSON contains nested data. Jazz has some allusion to mapping to a structure but not with nested data.
Is there an example or a common practice to decode JSON in Elixir similar to Go's usage:
type Response struct {
Data struct {
Children []struct {
Data Item
}
}
}
type Item struct {
Title string
URL string
Comments int `json:"num_comments"` #mapping to another field label
}
struct(Item, item_map_from_json)?response["children"] |> convert_items_to_struct(). However, if you need to preserve the whole structure, you can useupdate_in/2to traverse to a known nested level and update it. For exampleupdate_in response["children"], &convert_items_to_struct/1.