2015-11-20 3 views
3

Борьба, чтобы найти правильный путь для завершения моего декодера. Я начинаю с данными формыElm: Декодирование Json до простой структуры записи

[{_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. Благодарны за некоторые окончательные советы

ответ

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 
2

Я не уверен, что вы можете сделать намного лучше; вы пытаетесь разобрать формат, который может выражать вещи, которые вы не можете представлять в своих типах, поэтому ваш единственный вариант - сбой.

Чтобы удовлетворить образцовые боги, возможно, опустите предложение otherwise с изображением декодера fail? (http://package.elm-lang.org/packages/elm-lang/core/3.0.0/Json-Decode#fail)

+0

Спасибо, я действительно добавил шаблон комбинезона, но на самом деле надеюсь, что смогу найти более гибкий выход –

Смежные вопросы