Created
October 13, 2016 14:54
-
-
Save jackysee/f727fe04b912306eefd1bbd99e0c31d8 to your computer and use it in GitHub Desktop.
Decode different format of json in elm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Html exposing (text) | |
import Json.Decode as Decode exposing ( Decoder, (:=), at ) | |
jsonString1 = | |
"{ \"enclosure\" : { \"url\": \"aaa\" } }" | |
jsonString2 = | |
"{ \"enclosure\" : [ {\"url\": \"ccc\"}, {\"url\" : \"bbb\"} ] }" | |
type alias Enclosure = | |
{ url : String} | |
main = | |
let | |
a = Decode.decodeString decoder jsonString1 | |
url1 = getUrl a | |
b = Decode.decodeString decoder jsonString2 | |
url2 = getUrl b | |
in | |
text <| "Hello, " ++ url1 ++ "," ++ url2 | |
decoder : Decoder Enclosure | |
decoder = | |
Decode.oneOf | |
[ "enclosure" := enclosureDecoder | |
, ("enclosure" := Decode.list enclosureDecoder ) | |
`Decode.andThen` | |
(\list -> | |
let | |
first = List.head list | |
in | |
case first of | |
Just f -> Decode.succeed f | |
Nothing -> Decode.fail "failed" | |
) | |
] | |
enclosureDecoder : Decoder Enclosure | |
enclosureDecoder = | |
Decode.object1 Enclosure | |
( "url" := Decode.string ) | |
getUrl : Result String Enclosure -> String | |
getUrl a = | |
case a of | |
Ok e -> | |
e.url | |
Err err -> | |
"error" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment