Elm:将 Json 解码为简单的记录结构

Elm: Decode Json to a simple record structure

努力寻找正确的方法来完成我的解码器。我从

形式的数据开始
[{_id:'interests', [{obj1}, {obj1}]}
,{_id:'countries', [{obj2}, {...}]} 
,{_id:'sections', [{obj3}, {...}]}]

我想去 Decoder Summary 那里

type alias Summary =
    { sections : List Section
    , interests : List Interest
    , countries : List Country
    }

到目前为止,我能得到的最好结果是这种输出:

[ Interests (List Interest), Countries (List Country), Sections (List Section)]

但这仍然需要一些相当脆弱的模式匹配(依赖于数组的一致顺序 ,因此对于 0.16 是非常有问题的)。为此,我使用

summaryItemDecoder : String -> Decoder SummaryInfo
summaryItemDecoder item =
    let dec =
        case item of
            "sections" -> Json.map Sections sectionsDecoder
            "interests" -> Json.map Interests interestsDecoder
            "countries" -> Json.map Countries countriesDecoder
    in ("data" := dec)

listSummaryDecoder : Decoder (List SummaryInfo)
listSummaryDecoder =
    ("_id" := string) `Json.andThen` summaryItemDecoder
    |> list

完整代码here。感谢最后的提示

我不确定你能做得更好;您正在尝试解析一种可以表达您无法在您的类型中表示的内容的格式,因此您唯一的选择就是失败。

为了让模式匹配的大神们满意,或许在fail解码器中加入一个otherwise子句? (http://package.elm-lang.org/packages/elm-lang/core/3.0.0/Json-Decode#fail)

您可以将信息列表折叠成摘要。

type Interest = Interest
type Section = Section
type Country = Contry

type Info =  Interests (List Interest) | Countries (List Country) | Sections (List Section) 


type alias Summary =
    { sections : List Section
    , interests : List Interest
    , countries : List Country
    }

emptySummary : Summary
emptySummary = 
    { sections = []
    , interests = []
    , countries = []
    }


toSummary : List Info -> Summary
toSummary xs = 
  let 
    insert info sum =
      case info of 
        Sections ss -> { sum | sections = ss }
        Interests is -> { sum | interests = is }
        Countries cs -> { sum | countries = cs } 

  in
    List.foldl insert emptySummary xs

infoList : List Info
infoList = []

summary = toSummary infoList