【问题标题】:Elm: Decode Json to a simple record structureElm:将 Json 解码为简单的记录结构
【发布时间】:2015-11-20 07:55:41
【问题描述】:

努力寻找正确的方法来完成我的解码器。我从表单的数据开始

[{_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。感谢一些最后的提示

【问题讨论】:

    标签: elm


    【解决方案1】:

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

    为了满足模式匹配之神,也许在 fail 解码器中删除 otherwise 子句? (http://package.elm-lang.org/packages/elm-lang/core/3.0.0/Json-Decode#fail)

    【讨论】:

    • 谢谢,我确实添加了一个整体图案,但真的希望我能找到更灵活的输出
    【解决方案2】:

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

    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 
    

    【讨论】:

      猜你喜欢
      • 2017-04-11
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-02
      • 1970-01-01
      • 2018-07-02
      • 2018-12-07
      相关资源
      最近更新 更多