2017-10-29 89 views
0

我正在处理我的第一个Elm应用程序。Elm:将本地JSON文件解码为字典

我想使用本地JSON文件作为查找表。该文件将天气状况(字符串)与建议的衣服(列表)进行匹配。

编辑(澄清问题):基于2015年以前的一些SO问题,我尝试过使用Http.get获取内容,然后使用Decode.dict创建Dict。使用Http模块来获取本地文件似乎很奇怪。这个方法,包括我在下面使用的Http.send正确吗?

我也很难找到一个解码器的例子,它可以用于像我这样的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 
+1

考虑通过将JSON作为初始化一个标志? –

回答

0

Decode.dictdict为了处理该字典的密钥进行解码需要Decoderdict自动将键提取为字符串。

我转换的代码:

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

(list string)是解码器,将解码器串的名单从JSON为List String