Jeffrey Kandel
Jeffrey Kandel

Reputation: 460

Elm: decode local JSON file into dict

I'm working on my first Elm app.

I want to use a local JSON file as a lookup table. The file matches weather conditions (a string) to suggested clothing (a list).

EDIT (clarifying the question): Based on some earlier SO questions from 2015 I've tried using Http.get to get the contents and then Decode.dict to create the Dict. It seems strange to use an Http module to ingest a local file. Is this methodology, including the Http.send I use below correct in Elm?

I am also having a hard time finding an example of a decoder that would work for a JSON file like the one I have. Any pointers would be appreciated.

JSON

{
     "male,10,overcast,light wind...": ["Winter Cap", "Light Jacket"...], 
     "female,30,partly cloudy...": ["Winter Cap", "Sunglasses", ...]
}

CODE

type alias ClothingDict =
     Dict String List

clothingUrl: String
clothingUrl =
  "./clothing.json"

getClothingDict : Cmd Msg
getClothingDict =
  let
    url = clothingUrl
  in
    Http.send SetClothing (Http.get url decodeClothingResponse)

type alias ClothingResponse =
    { clothingOptions: ClothingDict }

decodeClothingResponse : Decoder ClothingResponse
decodeClothingResponse =
    Decode.dict ClothingResponse

Upvotes: 0

Views: 802

Answers (1)

Jeffrey Kandel
Jeffrey Kandel

Reputation: 460

Decode.dict or dict takes a Decoder in order to handle decoding the keys of the Dict. dict automatically extracts the keys as strings.

I converted the code to:

decodeClothingResponse : Decoder (Dict String (List String))
decodeClothingResponse =
    dict (list string)

(list string) is a decoder that will decoder a list of string from json in to a List String

Upvotes: 1

Related Questions