2016-12-13 1 views
0

私はJSONからパースレコードを持っている:私は代わりに生の文字列のpubDateためDateを使用したい場合は解析するときに文字列のJSON値をオブジェクトに展開するにはどうすればよいですか?

import Json.Decode exposing (..) 
import Json.Decode.Pipeline exposing (..) 

type alias Article = { 
    pubDate: String 
} 

articleDecoder : Decoder Article 
articleDecoder = 
    decode Article 
     |> required "pubDate" string 

は今、どのように私はDate.fromStringでJSON値を「膨らませる」ようにコードを変更できますか?これが動作するように見えます

答えて

1

用語

というような用語は、エルムの用語集にを膨らまない存在です。

デコード JSON文字列またはJavaScritptオブジェクト。

Elmには何もありません。

したがって、フォーマットされた日付の文字列をDateタイプのデータ構造にデコードする必要があります。今日のよう

実装

0.18.0Date.fromStringコアからあなたは私が名前空間を維持していますISO 8601

から、より信頼性の高い日付解析用justinmimbs/elm-date-extraモジュールからDate.Extra.fromIsoStringを使用する必要がありますproven to be unreliable.

です明快さ。

dateDecoder : Decoder Date 
dateDecoder = 
    Json.Decode.string 
     |> Json.Decode.andThen 
      (\s -> 
       case Date.Extra.fromIsoString s of 
        Err e -> 
         Json.Decode.fail e 

        Ok d -> 
         Json.Decode.succeed d 
      ) 
0

type alias Article = { 
    pubDate: Date 
} 

articleDecoder : Decoder Article 
articleDecoder = 
    decode Article 
     |> required "pubDate" pubDateDecoder 

pubDateDecoder : Decoder Date.Date 
pubDateDecoder = 
    string |> andThen (\s -> 
     case Date.fromString s of 
      Err e -> fail e 
      Ok d -> succeed d 
     ) 
関連する問題