将嵌套的JSON有效负载映射到Elixir中的结构 [英] Map a nested JSON payload to a struct in Elixir

查看:91
本文介绍了将嵌套的JSON有效负载映射到Elixir中的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Golang教程geddit移植到Elixir.我使用Dartlang取得了成功,但是Elixir在地图和地图上的操作清单让我感到困惑.

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.

使用HTTPoison和JSEX,我有以下代码:

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

我的困难是将JSON主体解析为适当的结构,其中JSON包含嵌套数据. Jazz暗示了映射到结构而不是嵌套数据的情况.

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.

是否有一个示例或一种常见的做法来在Elixir中解码JSON,类似于Go的用法:

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
}

推荐答案

使用Poison JSON库,我能够部分到达那里来处理嵌套:

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.

这篇关于将嵌套的JSON有效负载映射到Elixir中的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆