【问题标题】:Elm: decode local JSON file into dictElm:将本地 JSON 文件解码为 dict
【发布时间】:2017-10-29 01:56:57
【问题描述】:

我正在开发我的第一个 Elm 应用程序。

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

编辑(澄清问题):根据 2015 年的一些早期 SO 问题,我尝试使用 Http.get 获取内容,然后使用 Decode.dict 创建字典。使用 Http 模块摄取本地文件似乎很奇怪。这种方法,包括我在下面使用的 Http.send 在 Elm 中是否正确?

我也很难找到一个解码器的例子,它可以用于像我所拥有的那样的 JSON 文件。任何指针将不胜感激。

JSON

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

代码

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

【问题讨论】:

  • 考虑将 json 作为标志传递给 init?

标签: json decode elm


【解决方案1】:

Decode.dictdict 采用 Decoder 来处理字典的密钥解码。 dict 自动将键提取为字符串。

我将代码转换为:

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

(list string) 是一个解码器,它将字符串列表从 json 解码为 List String

【讨论】:

    猜你喜欢
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 2013-11-23
    • 2018-07-22
    • 2017-04-11
    • 2018-12-07
    • 1970-01-01
    相关资源
    最近更新 更多