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

3

我正在努力寻找正确的方法来完成我的解码器。我从以下格式的数据开始:

[{_id:'interests', [{obj1}, {obj1}]}
,{_id:'countries', [{obj2}, {...}]} 
,{_id:'sections', [{obj3}, {...}]}]

我想要到达一个解码器摘要
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

完整代码在这里。感激一些最后的提示。

2个回答

2

谢谢,我确实添加了一个全覆盖模式,但是真的希望能找到更灵活的输出。 - Simon H

0
您可以将信息列表折叠成摘要。
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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接