我正在研究我的第一个榆树应用程序。
我想使用本地JSON文件作为查找表。该文件将天气条件(字符串)与建议的服装(列表)相匹配。
编辑(澄清问题):基于2015年的一些早期SO问题,我尝试使用Http.get获取内容,然后使用Decode.dict创建Dict。使用Http模块来摄取本地文件似乎很奇怪。这种方法,包括我在下面使用的Http.send
在Elm中是否正确?
我也很难找到一个解码器的例子,它可以用于像我这样的JSON文件。任何指针都会受到赞赏。
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
答案 0 :(得分:1)
Decode.dict
或dict
需要Decoder
才能处理解码Dict的密钥。 dict
会自动将密钥提取为字符串。
我将代码转换为:
decodeClothingResponse : Decoder (Dict String (List String))
decodeClothingResponse =
dict (list string)
(list string)
是一个解码器,用于解码从json到List String
的字符串列表