Map a nested JSON payload to a struct in Elixir

喜夏-厌秋 提交于 2020-01-02 03:51:07

问题


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
}

回答1:


Using the Poison JSON library I was able to get partly there for handling the nesting:

def handle_response(%{status_code: 200, body: body}) do
    json = Poison.decode!(body, as: %{"data" => %{"children" => [%{"data" => Redditex.Item}]}})
    items = Enum.map( json["data"]["children"], fn (x) -> x["data"] end )
end

Enumertion is necessary to remove the anonymous structs and the remapping of the field names has not shown as a native solution. A work path forward nonetheless.



来源:https://stackoverflow.com/questions/25142735/map-a-nested-json-payload-to-a-struct-in-elixir

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!